I have this simple model:
class Profile(models.Model):
bio = models.CharField(max_length=300, blank=False)
location = models.CharField(max_length=50, blank=
edu = models.CharField(max_length=250, blank=True, null=False)
profession = models.CharField(max_length=50, blank=True)
profile_image = models.ImageField(
upload_to=upload_image, blank=True, null=False)
def __str__(self):
try:
return str(self.pk)
except:
return ""
and a User model:
class User(AbstractBaseUser, UserTimeStamp):
first_name = models.CharField(max_length=50, blank=False, null=False)
email = models.EmailField(unique=True, blank=False, null=False)
profile = models.OneToOneField(Profile, on_delete=models.CASCADE)
uuid = models.UUIDField(
db_index=True,
default=uuid_lib.uuid4,
editable=False
)
is_admin = models.BooleanField(default=False, blank=False, null=False)
is_staff = models.BooleanField(default=False, blank=False, null=False)
is_active = models.BooleanField(default=True, blank=False, null=False)
objects = UserManager()
USERNAME_FIELD = "email"
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, perm_label):
return True
As you can see in User model I have a OneToOneField to Profile.
but in Profile model I can't access user instance to just use its email in str method. something like this:
def __str__(self):
return self.user.email
How can I do this? sometime these relations are confusing to me.
UPDATED
Yes self.user.email works well. but the problem is something else.
I have two type of users. users and teachers.
and each of them has field profile in their model. so if I say:
def __str__(self):
return self.user.email
It just returns email of user instances. what about teachers?
user model:
class User(AbstractBaseUser, UserTimeStamp):
profile = models.OneToOneField(Profile, on_delete=models.CASCADE, related_name='user_profile')
teacher model:
class Teacher(AbstractBaseUser, UserTimeStamp):
profile = models.OneToOneField(Profile, on_delete=models.CASCADE, related_name='teacher_profile')
profile model:
def __str__(self):
if hasattr(self, 'user_profile'):
# profile belong to user
print(self.user_profile.pk)
elif hasattr(self, 'teacher_profile'):
# profile belong to teacher
print(self.teacher_profile.pk)
Related
I am using a custom user model and I have anther Enquiry model. I want that is the login user type is_service_provider I want to fetch data of service provider who had login in the panel. I don't know how to do this.
here is my models.py
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=254,unique=True)
name = models.CharField(max_length=254, null=True)
email = models.EmailField(max_length=254, null=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_Customer = models.BooleanField(default=False)
is_Service_Provider = models.BooleanField(default=False)
last_login = models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'username'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def get_absolute_url(self):
return "/users/%i/" % (self.pk)
def get_username(self):
return self.username
class Enquiry(models.Model):
name = models.CharField(max_length=254 , null=False)
email = models.EmailField(max_length=254, null=False)
phone_no = models.IntegerField(null=False)
service_requied = models.ForeignKey('accounts.Category', on_delete=models.CASCADE, null=False)
subcategory = models.ForeignKey('accounts.SubCategory', on_delete=models.CASCADE, null=False)
country = models.ForeignKey('accounts.Country', on_delete=models.CASCADE, null=False)
state =models.ForeignKey('accounts.State', on_delete=models.CASCADE, null=False)
city = models.ForeignKey('accounts.City', on_delete=models.CASCADE, null=False)
address = models.CharField(max_length=254, null=False)
defects = models.TextField(max_length=254, null=False)
service = models.ForeignKey('accounts.User', on_delete=models.CASCADE, null=False)
def __str__(self):
return self.service.username
Here is my views.py
#login_required
def enquiry(request):
user = Enquiry.objects.all()
data = request.user
return render(request, 'service-provider-panel/enquiry.html', {'user' : user, 'data':data})
i want to add in only one user from Available classic to Chosen classic but not from admin page from view when user click on button
I tried this
pro = Profile(user=request.user)
pro.classic.add(name='Frank Sinatra-i love you baby')
but i get tthis error
Before adding any objects to a many-to-many relation, the both side of many-to-many objects must obtain their id, so they should be saved first.
Another problem in this code is you need to construct a Classic object before you add it to chosen ones. The add method receives objects, not parameters of model constructor.
May following code example helps you:
pro, _ = Profile.objects.get_or_create(user=request.user)
your_classic = Classic.objects.create(name='Frank Sinatra-i love you baby')
pro.classic.add(your_classic)
give me this error
mu model code
from django.db import models
# Create your models here.
from django.utils import timezone
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class RequestSong(models.Model):
music = models.CharField(max_length=150, blank=False, null=False)
stampDate = models.DateTimeField(default=timezone.now, blank=False, null=False)
def __str__(self):
return self.music
class HelpUser(models.Model):
email = models.EmailField(blank=False, null=False)
helpMessege = models.TextField(blank=False, null=False)
stampDate = models.DateTimeField(default=timezone.now)
def __str__(self):
return str(self.email)
class Language(models.Model):
language = models.CharField(
max_length=2,
choices=[
('AR', 'Arabic'),
('EN', 'English'),
],
default='AR'
)
def __str__(self):
return self.language
class ChillOut(models.Model):
name = models.CharField(max_length=50, blank=False, null=False)
music = models.FileField(upload_to='', max_length=100, blank=True, null=True)
lang = models.ForeignKey(Language, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Sad(models.Model):
name = models.CharField(max_length=50, blank=False, null=False)
music = models.FileField(upload_to='', max_length=100, blank=True, null=True)
lang = models.ForeignKey(Language, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Happy(models.Model):
name = models.CharField(max_length=50, blank=False, null=False)
music = models.FileField(upload_to='', max_length=100, blank=True, null=True)
lang = models.ForeignKey(Language, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Romantic(models.Model):
name = models.CharField(max_length=50, blank=False, null=False)
music = models.FileField(upload_to='', max_length=100, blank=True, null=True)
lang = models.ForeignKey(Language, on_delete=models.CASCADE)
def __str__(self):
return self.name
class WorkOut(models.Model):
name = models.CharField(max_length=50, blank=False, null=False)
music = models.FileField(upload_to='', max_length=100, blank=True, null=True)
lang = models.ForeignKey(Language, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Classic(models.Model):
name = models.CharField(max_length=50, blank=False, null=False)
music = models.FileField(upload_to='', max_length=100, blank=True, null=True)
lang = models.ForeignKey(Language, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
classic = models.ManyToManyField(Classic, blank=True, null=True)
workOut = models.ManyToManyField(WorkOut, blank=True, null=True)
chillOut = models.ManyToManyField(ChillOut, blank=True, null=True)
romantic = models.ManyToManyField(Romantic, blank=True, null=True)
happy = models.ManyToManyField(Happy, blank=True, null=True)
sad = models.ManyToManyField(Sad, blank=True, null=True)
def __str__(self):
return str(self.user)
# class Favorite(models.Model):
# name = models.CharField(max_length=50, blank=False, null=False)
# fav = models.ForeignKey(ChillOut, on_delete=models.CASCADE)
# pro = models.ForeignKey(Profile, on_delete=models.CASCADE)
# def __str__(self):
# return self.name
def update_user_profile(sender, **kwargs):
if kwargs['created']:
user = Profile.objects.create(user=kwargs['instance'])
post_save.connect(update_user_profile,sender=User)
I have a user model which looks like this:
class User(AbstractUser):
first_name = models.CharField(max_length=70)
last_name = models.CharField(max_length=70)
middle_name = models.CharField(max_length=70, blank=True)
email = models.EmailField(
max_length=254,
unique=True,
verbose_name='Email Address',
blank=True
)
is_student = models.BooleanField(default=False, verbose_name='Student')
is_superuser = models.BooleanField(default=False, verbose_name='Administrator')
is_teacher = models.BooleanField(default=False, verbose_name='Teacher')
is_staff = models.BooleanField(default=False, verbose_name='Staff')
is_registrar = models.BooleanField(default=False, verbose_name='Registrar')
and in my StudentPorile model I have a field called class_advisor which is related to User model and I need to get the users with is_teacher field is True. Now, how do i filter class_advisor field to return Users only with is_teacher=True?
here's my StudentProfile model:
class StudentProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
lrn = models.CharField(max_length=20)
landline_number = models.CharField(max_length=11, null=True, blank=True)
mobile_number = models.CharField(max_length=11, null=True, blank=True)
address = models.TextField(max_length=300, blank=True)
mothers_name = models.CharField(max_length=50)
fathers_name = models.CharField(max_length=50)
contact_person_name = models.CharField(max_length=50)
contact_person_number = models.CharField(
max_length=12, verbose_name='Phone number of Contact Person')
# class_advisor = IM STUCK HERE
year_level = models.OneToOneField(Year_Level, on_delete=models.SET_NULL, null=True)
section = models.OneToOneField(Section, on_delete=models.SET_NULL, null=True)
This should return you a queryset of all the Users who have their is_teacher attribute set to True
User.objects.filter(is_teacher=True)
views.py
class MyView(View):
def get(self, request):
filtered_users = User.objects.filter(is_teacher=True)
return render(request, 'home.html', context={'users': filtered_users})
template.html
{% for user in users %}
{{user}}
{% endfor %}
I created Custom User model in django using below code
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
username = models.CharField(_("Username"), max_length=50, unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', ]
objects = CustomUserManager()
def __str__(self):
return self.email
And I also created another model for user profiles like below.
class UserProfile(models.Model):
user = models.OneToOneField(User, verbose_name=_("User"), on_delete=models.CASCADE)
first_name = models.CharField(_("First name"), max_length=50)
middle_name = models.CharField(_("Middle name"), max_length=50, blank=True, null=True)
last_name = models.CharField(_("Last name"), max_length=50)
dob = models.DateField(_("D.O.B"), auto_now=False, auto_now_add=False, blank=False, null=False)
profile_image = models.ImageField(_("Profile picture"), upload_to='user/profile/', blank=True)
webiste_link = models.URLField(_("Websites"), max_length=200, null=True, blank=True)
At last I created another model for Category like below.
class Category(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_(
"Author"), on_delete=models.CASCADE, related_name='blog_category')
title = models.CharField(_("Title"), max_length=50)
I want to auto save logged in user full name instead of user email address. By the way i used below code to auto save logged in user. It works but It only save user email address. But I want user full name instead of email or username.
obj.author = request.user
super().save_model(request, obj, form, change)
You could define a method in the UserProfile model to build this fullname, as you may need it in another function :
class UserProfile(models.Model):
user = models.OneToOneField(User, verbose_name=_("User"), on_delete=models.CASCADE)
[...]
def get_fullname(self):
return ' '.join([name for name in [
self.first_name,
self.middle_name,
self.last_name
] if name])
So you keep this way to save the user foreignkey in a Category:
obj.author = request.user
And later, to call the fullname on a category instance you can use :
# cat = Category.objects.first()
cat.author.userprofile.get_fullname()
You can add a filed called full_name in UserProfile model
Class UserProfile(models.Model):
user = models.OneToOneField(User, verbose_name=_("User"), on_delete=models.CASCADE)
first_name = models.CharField(_("First name"), max_length=50)
full_name = mdoels.CharField(_("Full name"),max_length=100)
middle_name = models.CharField(_("Middle name"), max_length=50, blank=True, null=True)
last_name = models.CharField(_("Last name"), max_length=50)
dob = models.DateField(_("D.O.B"), auto_now=False, auto_now_add=False, blank=False, null=False)
profile_image = models.ImageField(_("Profile picture"), upload_to='user/profile/', blank=True)
webiste_link = models.URLField(_("Websites"), max_length=200, null=True, blank=True)
def save(self,*args,**kwargs):
if not self.full_name:
self.full_name = self.first_name + " " + self.middle_name + " " + self.last_name
super().save(*args, **kwargs)
And then using author you can call the users full_name
models.py
class Hub(models.Model):
name = models.CharField(max_length=150)
def __str__(self):
return self.name
class User(AbstractUser):
is_client = models.BooleanField(default=False)
is_trainer = models.BooleanField(default=False)
username = models.CharField('username', max_length=150, unique=True)
email = models.EmailField(unique=True)
hub = models.ForeignKey(Hub, on_delete=models.CASCADE, blank=True, null=True)
hub_position = models.CharField(max_length=150, default="")
mentor = models.ForeignKey('self', on_delete=models.CASCADE, blank=True,null=True)
terms = models.BooleanField(blank=True, default=False)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email', 'terms']
def get_absolute_url(self):
return reverse('student:dashboard', kwargs={'pk': self.pk})
Confused on how to design the models here. Each User can belong to exactly one Hub.A hub has one leader, many excoms and many members ,all of them belongs to User .The hubs are added from the admin side.Leader can accept hub joining requests from excoms and members.
I'd add the user position as a choice field to the User, so you get a nice select box in the Admin.
class User(AbstractUser):
USER_POSITIONS = ((0, 'Regular'), (1, 'Leader'), (2, 'Excom'))
hub = models.ForeignKey(Hub, on_delete=models.CASCADE, blank=True, null=True)
hub_position = models.IntegerField(default=0, choices=USER_POSITIONS, ...)