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 %}
Related
I am working on a Django project which is something similar to Fiverr in its working. I have used abstractuser where there is a buyer and seller. The seller creates a gig then the buyer will go through the gig before placing an order. My issue is how to get the seller and place him in the order that the buyer will create from reading the gig. Currently I am using the system whereby the buyer will have to manually choose a gig from a list, which I think is not effective.
Here is my Models.py
`class User(AbstractUser):
is_buyer=models.BooleanField(default=False)
is_seller=models.BooleanField(default=False)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(default='avatar.jpg', null=True, blank=True)
about = models.CharField(max_length=100)
def __str__(self):
return self.user.username
class Gig(models.Model):
seller = models.ForeignKey(Profile, on_delete = models.CASCADE, null=False, blank=False)
category = models.ForeignKey('Category', on_delete = models.CASCADE, null=False, blank=False)
title = models.CharField(max_length=500, null=True, blank=True)
description = models.CharField(max_length=500, null=True, blank=True)
gig_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Order(models.Model):
buyer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=False, blank=False)
seller = models.ForeignKey(Gig, on_delete=models.CASCADE, related_name='+', null=False, blank=False)
title = models.CharField(max_length=500, null=True, blank=True)
description = models.CharField(max_length=500)
amount = models.IntegerField(max_length=50, blank=False)
is_ordered = models.BooleanField(default=False)
order_id = models.UUIDField(default=uuid.uuid4, unique=True, db_index=True, editable=False)
slug = models.SlugField(null=True)
def __str__(self):
return self.title`
And views.py where I am getting the submissions;
def createOrder(request):
profile = request.user.profile
form = CreateOrderForm()
if request.method == 'POST':
form = CreateOrderForm(request.POST, request.FILES)
if form.is_valid:
order = form.save(commit=False)
order.buyer = profile
order.save()
# form.save()
messages.info(request, 'Order Succesfully Created')
return redirect('create_order')
else:
messages.error(request, 'Order Not Created! Try Again Later')
context = {'form':form}
return render(request, 'users/create_order.html', context)
Any help will he highly appreciated.
I have a simple view for showing all the current users that are conditionally filtered based on the user type that is requesting the data.
models.py
class User(AbstractBaseUser, PermissionsMixin):
class SEX(models.TextChoices):
MALE = "MALE", "Male"
FEMALE = "FEMALE", "Female"
class TYPES(models.TextChoices):
...
type = models.CharField(
_("User Type"), max_length=50, choices=TYPES.choices, default=None, blank=True, null=True)
sex = models.CharField(
_("Sex Type"), max_length=50, choices=SEX.choices, default=None, blank=True, null=True)
email = models.EmailField(
_("Your Email"), max_length=254, unique=True, default=None, blank=True, null=True)
student_id = models.CharField(
_("student id"), unique=True, max_length=10, blank=True, null=True)
firstname = models.CharField(max_length=250, blank=False, null=True)
middlename = models.CharField(max_length=250, blank=True, null=True)
lastname = models.CharField(max_length=250, blank=False, null=True)
# grade = models.ForeignKey(Grade, verbose_name=_(
# "grade"), on_delete=models.CASCADE, blank=True, null=True)
room = models.ForeignKey(Class, verbose_name=_(
"class"), on_delete=models.CASCADE, blank=True, null=True)
phone = models.CharField(
_("phone number"), max_length=13, blank=True, null=True)
age = IntegerRangeField(min_value=1, max_value=99,
default=25, blank=True, null=True)
owns = models.ManyToManyField(School, verbose_name=_(
"School_owner"), related_name='Schoolowner', blank=True)
workes = models.ForeignKey(School, verbose_name=_(
"School_workes"), related_name='Schoolworkes', on_delete=models.SET_NULL, blank=True, null=True)
learns = models.ForeignKey(School, verbose_name=_(
"School_learns"), related_name='Schoollearns', on_delete=models.SET_NULL, blank=True, null=True)
image = models.ImageField(
_("photo"), upload_to='user/pp', max_length=None, blank=False, null=True)
joined_date = models.DateTimeField(
_("created at"), auto_now=False, auto_now_add=True)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
last_login = models.DateTimeField(
_("last login"), auto_now=True, auto_now_add=False)
serializers.py
class MyAccountSerializer(serializers.ModelSerializer):
image = serializers.ImageField()
class Meta:
model = User
fields = ['id', 'sex', 'type', 'phone', 'image', 'email', 'student_id', 'firstname', 'middlename', 'lastname',
'image', 'joined_date', 'is_active', 'is_superuser', 'is_staff', 'last_login']
views.py
class TeacherList(generics.ListAPIView):
permission_classes = [IsAuthenticated, ]
serializer_class = ListUsersSerializer
queryset = User.objects.filter(type=User.TYPES.TEACHER)
A simple filter like this works without any errors but since I need to filter the response based on the requesting user
this is what I want to use
class TeacherList(generics.ListAPIView):
permission_classes = [IsAuthenticated, ]
serializer_class = ListUsersSerializer
# queryset = User.objects.filter(type=User.TYPES.TEACHER)
def get_queryset(self):
request = self.request.user
if request.type == User.TYPES.OWNER:
queryset = User.objects.filter(
type=User.TYPES.TEACHER, workes=request.owns)
elif request.type in [User.TYPES.STAFF, User.TYPES.DIRECTOR, User.TYPES.VICE_DIR]:
queryset = User.objects.filter(
type=User.TYPES.TEACHER, workes=request.workes)
return queryset
however this shows me an error that goes like this:
Field 'id' expected a number but got <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x0000019D64AE7D60>.
I suspect it has something to do with a many-to-many field of which I have one named owns which is what I'm using to filter in 1 of the conditions but don't know why it throws error
I think instead of
queryset = User.objects.filter(
type=User.TYPES.TEACHER, workes=request.owns)
You should try something like:
queryset = User.objects.filter(
type=User.TYPES.TEACHER, workes__in=request.owns.all())
or
queryset = User.objects.filter(
type=User.TYPES.TEACHER, workes__in=request.owns.values_list("id", flat=True))
It should match all Users that have all ids from request.owns ids.
The problem arises while creating new users. It says related object does not exist.
accounts model
class Accounts(AbstractBaseUser):
username = models.CharField(max_length=30, unique=True)
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
date_created = models.DateTimeField(
verbose_name='date_joined', auto_now_add=True)
last_login = models.DateTimeField(
verbose_name='last_login', auto_now_add=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
# setting username as a key to login. Note: email can also be used in it
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['first_name', 'last_name', 'email']
store model
class Customer(models.Model):
username = models.OneToOneField(
Accounts, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=100, null=True)
email = models.CharField(max_length=100, null=True)
def __str__(self):
return self.name
in your views as the error says you tried
customer = request.user.customer
while you have nothing namer customer a all in your Customer class but a username
so either :
change your query in the views to :
customer = request.user.username
or
change the username in your class to customer :
customer = models.OneToOneField( Accounts, on_delete=models.CASCADE, null=True,
blank=True)
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 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