I have a custom user model extending Abstract User
. There is another model storing the user types. There are two types of users: clients(id is 1) and Professional(id is 2). I am trying to restrict the professionals from seeing a few links. These links are classified to the clients only. I am trying to tweak the LoginRequiredMixin and use it in my views.
Here is the Mixin I wrote:
from django.shortcuts import redirect, render
from django.contrib.auth.mixins import AccessMixin
class ClientLoginMixin(AccessMixin):
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated or not request.user.usertype_id == 2:
return render(request, 'clients/restricted.html')
return super().dispatch(request, *args, **kwargs)
Here is the original Mixin:
from django.shortcuts import redirect, render
from django.contrib.auth.mixins import AccessMixin
class ClientLoginMixin(AccessMixin):
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return render(request, 'clients/restricted.html')
return super().dispatch(request, *args, **kwargs)
Here are the models:
class UserList(AbstractUser):
UserMiddleName = models.CharField(max_length=100, null=True)
usertype = models.ForeignKey(UserType, on_delete=models.CASCADE)
Application = models.ForeignKey(AppliationList,on_delete=models.CASCADE, null=True)
class UserType(models.Model):
UserType = models.CharField(max_length=15, choices=user_type, default="Customer")
UpdatedDate = models.DateField(auto_now_add=True)
But this gives me an error User has no attribute usertype_id
. I tried printing the user and there was a usertype_id present.
{'Application_id': 2, 'ContactCell': '8697707501', 'UserMiddleName': None, 'date_joined': '2021-02-19T18:46:03.966', 'email': '[email protected]', 'first_name': 'Ankur', 'id': 1, 'is_active': True, 'is_authenticated': True, 'is_staff': True, 'is_superuser': False, 'last_login': '2021-02-23T14:56:19.378', 'last_name': 'Ankur', 'password': 'pbkdf2_sha256$180000$PSvLXc0SrBQE$sur9h4EBcXM9mCKJUjkM17TsTqSRfxfvGrWw26OBWIQ=', 'type': 'Client', 'username':
'[email protected]', 'usertype_id': 1}
Can someone please point me out what am I doing wrong here?
Source: Python Questions