I am displaying user information to the admin dashboard I want to order Users by their join date.
and on another page, I want to display only 10 users information which are recently logged in.
I am filtering user data like this:
data = Profile.objects.filter(Q(user__is_superuser=False), Q(user__is_staff=False))
Model.py
class Profile(models.Model):
user = models.OneToOneField(User,default="1", on_delete=models.CASCADE)
image = models.ImageField(upload_to="images",default="default/user.png")
def __str__(self):
return f'{self.user} profile'
Please help me to do this.
I am assuming you have certain fields like last login in Profile to track login history.
Use:
user__last_login
Now you can filter as:
data = Profile.objects.filter(Q(user__is_superuser=False), Q(user__is_staff=False)).order_by('-user__last_login')[:10]
user.last_login
you can order user queryset based on last_login field and take first 10 using [:10] at end of queryset
Related
I am building a BlogApp and I am trying to get all the users that's profile's BooleanField are True.
What i am trying to do:-
I made a feature of Users that are banned and I made a BooleanField for each user, AND i am trying to get all the Users that's profile's BooleanValue is True.
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True)
block_users = models.BooleanField(choices=BLOCK_CHOISES,default=False)
The Problem
def block_users(request):
profile = request.user.profile
blocked = Profile.objects.filter(block_users=profile.block_users)
context = {'blocked':blocked}
return render(request, 'blocked.html', context)
When i runthis code, This only shows me user that's value is False. BUT i want users that's Value is True.
I have no idea how to get it.
Thanks in Advance.
Any help would be Appreciated.
It looks like you are trying to list out users as per logged in user. I mean, if logged in user is Blocked, it will list blocked users and if not it will list not-blocked users.
this instead:
In your models.py, create a related_name
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile_user",unique=True)
block_users = models.BooleanField(choices=BLOCK_CHOISES,default=False)
In views.py, when you will do "request.user.profile_user.block_users", it will give logged in users blocking status.
Now, if you want users which are blocked, filter directly with True.
Profile.objects.filter(block_users=True)
I have this model in accounts.models:
from django.contrib.auth.models import User
class UserProfile(BaseModel):
user = models.OneToOneField(
User, related_name="user_profile", on_delete=models.CASCADE
)
# ...
def __str__(self) --> str:
return self.user.username
And the following in memberships.models:
class ExternalServiceProfileMembership(BaseModel):
created_at = models.DateTimeField()
expires_at = models.DateTimeField()
profile = models.ForeignKey(
"accounts.UserProfile",
on_delete=models.CASCADE,
related_name="ext_memberships",
)
plan = models.ForeignKey("memberships.MembershipPlan", on_delete=models.CASCADE)
ext_subscription_id = models.CharField(max_length=128)
When I try to access the admin view of an individual ExternalServiceProfileMembership object (for example: http://localhost:8000/admin/memberships/externalserviceprofilemembership/1/change/), the site gets stuck, eventually returning a 503. So I started out commenting out fields in the AdminModel, and once I remove profile, the object change view loaded fine.
I brought back profile into AdminModel but removed UserProfile's __str__() method, and it also worked. Which makes me think the whole issue is with this method; but I have no idea why.
Any help is appreciated!
On the change page for ExternalServiceProfileMembership, the profile dropdown displays the name of every user. This causes one extra query for every user in the dropdown.
The quick fix is to add 'profile' to readonly_fields, autocomplete_fields or raw_id_fields. These three options mean that a single profile is displayed on the change form, so there is only one extra query to fetch the user.
Another approach, which is more complicated, is to create a custom form that overrides the queryset to use select_related to fetch all of the users, then use that form in your model admin.
How to pass codeval variable from models.py to views.py:
in models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
import random
from django.core.mail import send_mail
class UserProfile(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length=100, default='')
city = models.CharField(max_length=100, default='')
website = models.URLField(default='')
mobile = models.IntegerField(default=0)
code = models.IntegerField(default=0)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])
codeval = random.randint(111111,999999)
user_profile.code = codeval
user_profile.save()
receiver = User.objects.get(id=user_profile.user_id).email
send_mail(' Confirm your account on Abolombon',
'Thanks for signing up with Abolombon! Your Abolombon verification code is:\n %s\n\n Thank you\nAbolombon.com'%(codeval),
'testpurpose2040#gmail.com',
[receiver])
post_save.connect(create_profile, sender=User)
in views.py
def verification(request, args=codeval):
return render(request,'website/verification.html',{'args':args})
I am making an e-commerce site in django where I need user registration option. For this purpose I am using django's build in user registration form. But I need to store some additional info about user like contact number, city etc. I also want to verify user sending a 6 digit code to their corresponding email address.
But in django's build in form their is no field to store verification code. So I have created UserProfile model to serve this purpose. And have created code field to store 6 digit random number.
I want to store this random number into code field and also send it to the user email address. And when user will enter the code a function will verify it with the stored one. For this I need key to retrieve the code from the db. So I want to pass this key to the views.py.
Thank you
If I am interpreting your question correctly, you want UserProfile.objects.get(code=codeval). This will give you the actual profile, so if you want the id, just do UserProfile.objects.get(...).id.
Note that your current code could give multiple profiles the same code, so you should either prevent that or get all profiles that match using .filter instead of .get.
I created a working "Log in with facebook" setup with django-allauth. However, I want those new user accounts that allauth creates to not be activated automatically.
Basically I want to activate all new accounts from the Django admin pages.
What would be a best practice solution to this?
Thanks
How do you know that an account is activated or not? You need some kind of field in your User model.
Let's say that your field is called is_activated:
class User(BaseUser):
is_activated = models.BooleanField(default=False)
and that's it. This field's default value will be False which means that a created user is not activated by default.
Then, you can add this field to the admin page and toggle it from there.
Hope it helps!
I'd suggest what follows because when I made cogofly I had this huge problem where some people (few but some of them do) click sometimes on "log in with google" and sometimes on "log in with facebook" and this is the same person! So be careful with that and this solution will help you to avoid such problem. The only thing to remember: there's only one primary key for all social networks: the email.
Like it's written in the documentation, I'd make a OneToOne link to the User model.
From this I would suggest this:
precise the date of the first login
precise the date of the last login
precise if the account has been validated
Like this:
from django.contrib.auth.models import User
class Person(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
is_activated = models.BooleanField(default=False)
And make a social login model where you precise how the user logged in:
class SocialLogin(BaseModel):
S_GOOGLE = 1
S_FACEBOOK = 2
TAB_S_LOGIN = {
S_GOOGLE: _("Google"),
S_FACEBOOK: _("Facebook"),
}
logged_in = models.IntegerField(
choices=[(a, b) for a, b in list(TAB_S_LOGIN.items())],
default=S_GOOGLE)
date_first_login = models.DateTimeField(auto_now_add=True,
verbose_name=_('First login'))
date_last_login = models.DateTimeField(auto_now=True,
verbose_name=_('Last login'))
person = models.OneToOneField(Person, on_delete=models.CASCADE)
def logged_in_desc(self):
return SocialLogin.TAB_S_LOGIN[self.logged_in]
def __str__(self):
return '{} / {}'.format(
self.logged_in_desc(),
description if self.description is not None else '?')
so i currently have this as my profile model for each user.
class Profile(models.Model):
user = models.OneToOneField(User)
location = models.CharField(max_length=120, choices=LOCATIONS,null=True, blank=True)
picture = models.ImageField(upload_to=upload_location, null=True, blank=True)
how to i filer users depending on the choices given in the location field? So for example if the current user has London selected, in the template they will only see results of users/profiles with the same location.
Do i have to create an if statement or a for loop in the views.py? or do i use a q lookup? if anyone could give me some pointers or show me in the right direction that would be amazing!
thank you for any help in advance
It is recommended to filter the results in the view and based on your requirement, you can just use the native django queryset. You can create a view like this:
views.py
from django.contrib.auth.models import User
from django.shortcuts import render
def users(request):
location = request.GET.get('location', 'default_location')
users = User.objects.filter(profile__location=location)
return render(request, 'users.html', {'users': users})
So for example if you have a url /users/ for listing the users, passing the location parameter will filter your users /users/?location=london