Reputation: 359
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'),
Upvotes: 1
Views: 1051
Reputation: 476503
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,)
Upvotes: 2