In my application, I use a modified model User
with 3 more fields that I need.
from django.contrib.auth.models import AbstractUser
from django.db import models
import ldapdb.models
class User(AbstractUser):
cotisant = models.BooleanField(default=False)
nbSessions = models.IntegerField(default=0)
tel = models.CharField(max_length=20, default="")
I want people to be able to change their account settings (e.g. their password, email,, tel
...).
For this, I have a serializer like this:
from rest_framework import serializers
from django.contrib.auth.hashers import make_password
from coreapp.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password', 'cotisant', 'tel')
extra_kwargs = {
'password': {'write_only': True}
}
def validate_password(self, value: str):
return make_password(value)
And here is a view:
class UserViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
permission_classes = (IsSelfOrStaffPermission, TokenHasReadWriteScopeOrCreate,)
lookup_field = 'username'
def get_queryset(self):
current_user = self.request.user
if current_user.is_staff:
user_set = User.objects.all()
else:
user_set = User.objects.filter(username=current_user.username)
query = self.request.query_params.get('q', None)
if not query:
return user_set
return user_set.filter(
Q(username__icontains=query) |
Q(first_name__icontains=query) |
Q(last_name__icontains=query)
)
(This allows access to the user only for himself, unless he is a staff)
The problem is to update the parameter nbSessions
, the user must pay something in one of my applications.
How can I allow an application to set a parameter, but prevent the user from updating it directly?
. , Password Credential Flow , - .