is_active is not changing when custom user logged out - django

I am working on custom user model, but the logout feature is not synchronized with root password. is_active(here activated) variable is not changing to False when I logout and the superuser logged in Django admin gets logout when logout button is pressed in the front end user. How to fix this.
models.py
class Users(AbstractBaseUser, PermissionsMixin):
objects = UserManager()
mobile_no = models.IntegerField(_('MobNumber'), null=True, blank=True,unique=True)
email = models.EmailField(_('Email'), max_length=75, null=False, blank=False)
first_name = models.CharField(_('FirstName'), max_length=50, null=True, blank=True)
last_name = models.CharField(_('LastName'), max_length=70, null=True, blank=True)
role = models.CharField(_('Role'), max_length=70, null=True, blank=True)
location = models.CharField(_('Location'), max_length=70, null=True, blank=True)
date_time = models.DateTimeField(_('DateTime'), auto_now=True, null=True, blank=True)
activated = models.BooleanField(_('activated'), default=False)
is_admin = models.BooleanField(_('is_admin'), default=False)
is_itstaff = models.BooleanField(_('is_staff'), default=False)
def __unicode__(self):
return str(self.mobile_no)
def __str__(self):
return str(self.mobile_no)
def get_full_name(self):
return self.first_name + " " + self.last_name
class Meta:
ordering = ['-id']
#property
def is_staff(self):
return self.is_admin
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return self.is_admin
USERNAME_FIELD = 'mobile_no'
REQUIRED_FIELDS = ['role']
views.py
#login_required
def user_logout(request):
logout(request)
return HttpResponseRedirect(reverse('login'))

Related

Django Firebase Phone Number Auth

i have already Django project that completely works fine with custom user model phone and password for registering and sign up,
here i need to add firebase phone number authentication to send sms to user before register to my site ???
prettier any help here .
my custom user model
class MyUser(AbstractBaseUser):
email = models.EmailField(blank=True,null=True, verbose_name='Email Address',max_length=255 )
name = models.CharField(max_length=100,verbose_name= 'Username', )
last_name = models.CharField(blank=True,max_length=100,verbose_name= 'Family Name')
mobile = models.IntegerField(unique=True,verbose_name= 'Mobile Number')
governorate = models.CharField(blank=True,null=True,verbose_name='Governorate',max_length=255)
image =models.ImageField(blank=True,upload_to='profile_pics', default='profile_pics/avatar.png')
Is_Banned = models.BooleanField(default=False)
notification =models.BooleanField(default=False,verbose_name= 'Enable Notification')
language_choices =(
("Arabic", "Arabic"),
("English", "English"),
("Kurdish", "Kurdish"),
)
language = models.CharField( choices = language_choices,blank=True, default = 'Arabic',max_length=50,verbose_name= 'Language')
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'mobile'
REQUIRED_FIELDS = ['name','email']
def __str__(self):
return self.name
class Meta:
verbose_name_plural='Users'
def Adressess(self):
return 'adressess'
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
#property
def is_staff(self):
return self.is_admin
#property
def first_name(self):
return self.name

Why can't I change primary key in postgresql?

When I migrate the Django project model, I get the error:
there is no unique constraint matching given keys for referenced table "accounts_account
my models is:
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name='ایمیل', max_length=60, unique=True)
username = models.CharField(verbose_name='نام کاربری', max_length=30, unique=True)
phone_number = models.CharField(max_length=11, blank=True, null=True, default="")
profile_image = models.ImageField(default="profile.jpg", upload_to='profile/images')
# media/blog/images/img1.jpg
...
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = MyAccountManager()
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
in pgAdmin the Primary Key is not changeable

How to get the user associated to another model DRF. ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing

I want to check that the card number is exists and then get the associated user to that card number. A user can have multiple card numbers. How do I filter to get the user from the card number entered?
Models:
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name="Email Field", max_length=60, unique=True)
dateJoined = models.DateTimeField(
verbose_name="Date Joined", auto_now_add=True)
last_login = models.DateTimeField(verbose_name="Last Login", auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_verified = models.BooleanField(default=False)
# Parameters that we want to know about the user
first_name = models.CharField(verbose_name="First Name", max_length=100)
last_name = models.CharField(verbose_name="Lasst Name", max_length=100)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
objects = CustomUserManager()
def __str__(self):
return self.email
def tokens(self):
refresh = RefreshToken.for_user(self)
return {
'refresh': str(refresh),
'access': str(refresh.access_token)
}
def has_perm(self, perm, obj=None):
return self.is_superuser
def has_module_pers(self, app_label):
return True
class cardModel(models.Model):
user = models.ForeignKey(CustomUser, related_name='card_numbers',null = True, blank=True, on_delete=models.CASCADE)
card_number = models.IntegerField(
verbose_name="Card Number", blank=True, null=True, default=None, unique=True)
def __int__(self):
return self.card_number
Serializer:
class CheckCard(serializers.Serializer):
card_number = serializers.IntegerField(write_only=True)
class Meta:
fields = ['card_number','user']
read_only_fields = ['user']
Views:
class CheckCardAPI(APIView):
permission_classes = [AllowAny]
serializer_class = CheckCard
def post(self,request,*args,**kwargs):
serializer = self.serializer_class(data=request.data)
card_number = request.data.get('card_number','')
if cardModel.objects.filter(card_number=card_number).exists():
user = User.objects.filter(card_numbers=card_number)
tokens, created = Token.objects.get_or_create(user=user)
return Response({'token':tokens.key},status=status.HTTP_200_OK)
else:
return Response({'error':'card is not registered'},status=status.HTTP_404_NOT_FOUND)
You are looking for a single user based on card number, so your query
user = User.objects.filter(card_numbers=card_number)
returns a list. Maybe you would need to use
user = User.objects.get(card_numbers=card_number)
to get an object or use
value_list(id, flat=True)
with filter.

'User' object has no attribute 'user'

I have a User model
class User(AbstractBaseUser):
username = None
first_name = models.CharField(max_length=100, null=True, blank=True)
last_name = models.CharField(max_length=200, null=True, blank=True)
phone_regex = RegexValidator(regex=r'^09(\d{9})$',
message="Phone number must be entered in the format: '09111111111'")
phone = models.CharField(validators=[phone_regex], max_length=11, unique=True)
email = models.EmailField(max_length=255, null=True, blank=True)
# cart_number = models.PositiveBigIntegerField(null=True, blank=True) # shomare cart banki
birth_day = models.DateField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'phone'
REQUIRED_FIELDS = []
def __str__(self):
return self.phone
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
#property
def is_staff(self):
return self.is_admin
in view I want to have a class to get a User and update it
class UserRetrieveUpdateView(generics.RetrieveUpdateAPIView):
queryset = User.objects.filter(is_active=True)
serializer_class = UserSerializer
permission_classes = (IsOwner,)
when I want to test it with post man I give this error:
AttributeError at /account/1/
'User' object has no attribute 'user'
this is my url:
path('<int:pk>/', views.UserRetrieveUpdateView.as_view(), name='dashboard'),
You can not use IsOwner as permission_classes, since that will look for a .user attribute. You can implement a custom user model that will only allow to retrieve the logged in user:
from rest_framework import permissions
class IsThatUserPermission(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
return request.user == obj
and then use that IsThatUserPermission:
class UserRetrieveUpdateView(generics.RetrieveUpdateAPIView):
queryset = User.objects.filter(is_active=True)
serializer_class = UserSerializer
permission_classes = (IsThatUserPermission,)

Cannot resolve keyword 'is_active' into field

Trying to make a password reset view. I'm using the auth_views built in views ie PasswordResetView and PasswordResetConfirmView for resetting password. However I was getting this error
Cannot resolve keyword 'is_active' into field. Choices are: active, admin, email, first_name, id, last_login, last_name, logentry, password, staff, timetables
. Tried changing active to is_active and getting this error.
django.core.exceptions.FieldError: Unknown field(s) (active) specified for User
Not able to make migrations
models.py
class User(AbstractBaseUser):
first_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
email = models.EmailField(max_length=254, unique=True)
is_active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return self.email
def get_first_name(self):
if self.first_name:
return self.first_name
return self.email
def get_last_name(self):
return self.last_name
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
#property
def is_staff(self):
return self.staff
#property
def is_admin(self):
return self.admin
#property
def is_active(self):
return self.is_active
forms.py
class UserAdminChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = ('email', 'first_name', 'last_name',
'password', 'active', 'admin')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
Try to change is_active = models.BooleanField(default=True) to active = models.BooleanField(default=True) in your User class, and is_active property
see below
class User(AbstractBaseUser):
first_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
email = models.EmailField(max_length=254, unique=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)
#property
def is_active(self):
return self.active