Django Rest Framework: validate HiddenField CurrentUserDefault property - django

I am using DRF to create an API in a single page application.
I have a customer user class to which I have only added a is_manager flag and a managerEntity model where users that have the is_manager flag as True can create managerEntities becoming owners of them.
The problem is that I can't seem to figure out how to validate the data from the serializer before create method to check whether the is_manager is set or not. If set, the managerEntity should be created, if not, raise an exception.
class DeepmetricsUser(AbstractUser):
is_manager = models.BooleanField(default=False)
class managerEntity(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
team = models.ManyToManyField(get_user_model(), blank=True)
views.py
class managersEntityViewSet(viewsets.ModelViewSet):
queryset = managerEntity.objects.all()
serializer_class = managerEntityModelSerializer
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
return self.queryset.filter(Q(owner = self.request.user) | Q(team=self.request.user.id))
def create(self, request, *args, **kwargs):
serializer = managerEntitySerializer(data=request.data, context={"request": self.request})
serializer.is_valid(raise_exception=True)
res = serializer.save()
data = managerEntityModelSerializer(res).data
return Response(data, status=status.HTTP_201_CREATED)
serializer.py
class managerEntitySerializer(serializers.Serializer):
name = serializers.CharField(max_length=255)
owner = serializers.HiddenField(default=serializers.CurrentUserDefault())
def create(self, data):
res = managerEntity.objects.create(**data)
return res

You need to override the validate method in Serializer
def validate(self, attrs):
if not self.context["request"].user.is_manager:
raise serializers.ValidationError("Validation error")
return attrs

I found a solution that fits better my needs by using permissions. The answer provided by Shakeel is correct as I asked for validation and that should be done as he suggested but, what I really wanted to do was checking for enough clearance for the user to manipulate a resource, then, permissions is what's best fits:
class createManagerEntity(BasePermission):
message = "Not enough privilegies"
def has_permission(self, request, view):
return request.user.is_manager

Related

django rest framework - POST request causes 400 status code

I am trying to perform a POST request to create an article and I am getting this error Request failed with status code 400 Bad Request: /api/articles/create/.
An article needs 3 attributes to be created:
(1) title
(2) body
(3) author (the current user)
The router works fine since the POST request goes into the post method of the ArticleCreateView class. But I'm guessing that serializer.is_valid() is returning False for some reason.
Also print(request.data) returns {'title': 'hello', 'body': 'stuff'}
Another mystery about Django is, how does the serializer know if I want to get, create or update something? In all the examples I've seen, the serializer magically seems to know this.
class ArticleCreateView(CreateAPIView):
permission_classes = [IsAuthenticated]
def post(self, request):
serializer = ArticleSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors)
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = '__all__'
def create(self, validated_data):
author = self.context['request'].user
title = validated_data.get('title')
body = validated_data.get('body')
return Article.objects.create(author=author, title=title, body=body)
class Article(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
body = models.TextField(max_length=100)
date_updated = models.DateTimeField(auto_now=True)
date_created = models.DateTimeField(auto_now_add=True)
According to your serializer, the validation process needs author details, which is not passing through POST payload.
So, make the author field in the serializer a not required field by adding required=False or use a ReadOnlyField() or specify read_only_fields in Meta class. Also pass context data as #nishant mentioned
# views.py
class ArticleCreateView(CreateAPIView):
permission_classes = [IsAuthenticated]
def post(self, request):
serializer = ArticleSerializer(data=request.data, context={"request": request}) # change here
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors)
# serializer.py
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = '__all__'
read_only_fields = ('author',)
def create(self, validated_data):
author = self.context['request'].user
title = validated_data.get('title')
body = validated_data.get('body')
return Article.objects.create(author=author, title=title, body=body)
add this
serializer = ArticleSerializer(data=request.data, context={'request':request})

This QueryDict instance is immutable

I have a Branch model with a foreign key to account (the owner of the branch):
class Branch(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
name = models.CharField(max_length=100)
account = models.ForeignKey(Account, null=True, on_delete=models.CASCADE)
location = models.TextField()
phone = models.CharField(max_length=20, blank=True,
null=True, default=None)
create_at = models.DateTimeField(auto_now_add=True, null=True)
update_at = models.DateTimeField(auto_now=True, null=True)
def __str__(self):
return self.name
class Meta:
unique_together = (('name','account'),)
...
I have a Account model with a foreign key to user (one to one field):
class Account(models.Model):
_safedelete_policy = SOFT_DELETE_CASCADE
name = models.CharField(max_length=100)
user = models.OneToOneField(User)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name + ' - ' + self.create_at.strftime('%Y-%m-%d %H:%M:%S')
I've created a ModelViewSet for Branch which shows the branch owned by the logged in user:
class BranchViewSet(viewsets.ModelViewSet):
serializer_class = BranchSerializer
permission_classes = (permissions.IsAuthenticated,)
def get_queryset(self):
queryset = Branch.objects.all().filter(account=self.request.user.account)
return queryset
Now to create a new branch, I want to save account field with request.user.account, not with data sent from the rest client (for more security). for example:
def create(self, request, *args, **kwargs):
if request.user.user_type == User.ADMIN:
request.data['account'] = request.user.account
return super(BranchViewSet, self).create(request, *args, **kwargs)
def perform_create(self, serializer):
'''
Associate branch with account
'''
serializer.save(account=self.request.user.account)
In branch serializer
class BranchSerializer(serializers.ModelSerializer):
account = serializers.CharField(source='account.id', read_only=True)
class Meta:
model = Branch
fields = ('id', 'name', 'branch_alias',
'location', 'phone', 'account')
validators = [
UniqueTogetherValidator(
queryset=Branch.objects.all(),
fields=('name', 'account')
)
]
but I got this error:
This QueryDict instance is immutable. (means request.data is a immutable QueryDict and can't be changed)
Do you know any better way to add additional fields when creating an object with django rest framework?
As you can see in the Django documentation:
The QueryDicts at request.POST and request.GET will be immutable when accessed in a normal request/response cycle.
so you can use the recommendation from the same documentation:
To get a mutable version you need to use QueryDict.copy()
or ... use a little trick, for example, if you need to keep a reference to an object for some reason or leave the object the same:
# remember old state
_mutable = data._mutable
# set to mutable
data._mutable = True
# сhange the values you want
data['param_name'] = 'new value'
# set mutable flag back
data._mutable = _mutable
where data it is your QueryDicts
Do Simple:
#views.py
from rest_framework import generics
class Login(generics.CreateAPIView):
serializer_class = MySerializerClass
def create(self, request, *args, **kwargs):
request.data._mutable = True
request.data['username'] = "example#mail.com"
request.data._mutable = False
#serializes.py
from rest_framework import serializers
class MySerializerClass(serializers.Serializer):
username = serializers.CharField(required=False)
password = serializers.CharField(required=False)
class Meta:
fields = ('username', 'password')
request.data._mutable=True
Make mutable true to enable editing in querydict or the request.
I personally think it would be more elegant to write code like this.
def create(self, request, *args, **kwargs):
data = OrderedDict()
data.update(request.data)
data['account'] = request.user.account
serializer = self.get_serializer(data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
Do you know any better way to add additional fields when creating an object with django rest framework?
The official way to provide extra data when creating/updating an object is to pass them to the serializer.save() as shown here
https://docs.djangoproject.com/en/2.0/ref/request-response/#querydict-objects
The QueryDicts at request.POST and request.GET will be immutable when accessed in a normal request/response cycle. To get a mutable version you need to use QueryDict.copy().
You can use request=request.copy() at the first line of your function.

How can I pass user id into a serializer with request data?

I have a project that autenticate by oauth2_provider.ext.rest_framework.OAuth2Authentication. There is a token in the request headers for authenticating and identifying. I think I should not include user id in the request data explicitly when process a create action. But serializer need user info to create a new instance. So I include a user_id field in serializer, and put the value into the request.data dict after authenticating.
Is it good? Is there any better way?
serializers.py
class serializer(serializers.Serializer):
user = UserSerializer(read_only=True)
user_id = serializers.UUIDField(write_only=True)
content = serializers.CharField()
views.py
class CommentList(generics.ListCreateAPIView):
def create(self, request, *args, **kwargs):
request.data['user_id'] = request.user.id
return super(CommentList, self).create(request)
It is cleaner to override create(validated_data) in your serializer:
class CommentSerializer(serializers.Serializer):
...
def create(self, validated_data):
user = self.context['request'].user
comment = Comment.objects.create(
user=user,
**validated_data
)
return comment
See http://www.django-rest-framework.org/api-guide/serializers/#saving-instances
Then you do not need to customise your view, you can just use a generic view.
if user is authenticated then grab the value from request object and pass it to serializers by using get_serializer_context method
class CommentList(generics.ListCreateAPIView):
permission_classes = [IsAuthenticated]
def get_serializer_context(self):
return {'user_id':self.request.user.id}
class serializer(serializers.Serializer):
#your field, model
pass
def create(self, validated_data):
user_id = self.context['user_id']
return Comment.objects.create(user_id=user_id, **validated_data)

Update ONLY an auth.user field using request.user and django rest framework serializers

I'm currently writing an API using the django rest framework for the first time. However, I've run in to a problem when trying to update an object using only the request.user field
from what I understand, when updating an object with request.data fields, all you have to do is:
def put(self, request, pk, format=None):
chore = self.get_object(pk)
serializer = ChoreSerializer(chore, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
however, if I try to leave the data=request.data out, I'll get errors when trying to call .is_valid(). and in turn .save(). I managed to get around this error by serializing the object I want to change based on a primary key, and then de-serializing it again, using the serialized data like this:
seri = ChoreSerializer(chore)
serializer = ChoreSerializer(chore, data=seri.data)
if serializer.is_valid():
serializer.save(assigned_to=self.request.user)
return Response(serializer.data)
My question is whether this is actually the correct way to do this, or whether there's a better method
here's my Model:
class Chore(models.Model):
created = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=100, blank=True, default='')
owner = models.ForeignKey('auth.User', related_name='chores')
assigned_to = models.ForeignKey('auth.User',related_name='assigned_to', blank=True, null=True)
and here's my Serializer:
class ChoreSerializer(serializers.ModelSerializer):
class Meta:
model = Chore
fields = ('id', 'name', 'owner', 'assigned_to')
owner = serializers.ReadOnlyField(source='owner.username')
assigned_to = serializers.ReadOnlyField(source='assigned_to.username')
def create(self, validated_data):
return Chore.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.name = validated_data.get('name', instance.name)
instance.assigned_to = validated_data.get('assigned_to', instance.assigned_to)
instance.save()
return instance

Django Rest Framework update field

I am new to DRF and I am trying to write custom view / serializer that I can use to update just one field of user object.
I need to make logic just to update the "name" of the user.
I wrote serializer:
class ClientNameSerializer(serializers.ModelSerializer):
class Meta:
model = ClientUser
fields = ('name',)
def update(self, instance, validated_data):
instance.name = validated_data.get('name', instance.name)
instance.save()
return instance
This method is never called. I tried setting breakpoint there and debug it, but it is never called, even if I use PUT, POST or PATCH methods. If I add create method it is being called when I use POST.
This is how my view looks like:
class UpdateName(generics.CreateAPIView):
queryset = ClientUser.objects.all()
serializer_class = ClientNameSerializer
permission_classes = (permissions.IsAuthenticated,)
Does anyone have some suggestion? Thanks!
My models.py looks like this
class ClientUser(models.Model):
owner = models.OneToOneField(User,unique=True,primary_key=True)
phone_number = models.CharField(validators=[PHONE_REGEX],max_length=20,unique=True)
name = models.CharField(max_length=100,blank=True)
status = models.IntegerField(default=1)
member_from = models.DateTimeField('member from',auto_now_add=True)
is_member = models.BooleanField(default=False)
The definition of what methods the endpoint can accept are done in the view, not in the serializer.
The update method you have under your serializer needs to be moved into your view so you'll have something like:
serializers.py
class ClientNameSerializer(serializers.ModelSerializer):
class Meta:
model = ClientUser
views.py
class UpdateName(generics.UpdateAPIView):
queryset = ClientUser.objects.all()
serializer_class = ClientNameSerializer
permission_classes = (permissions.IsAuthenticated,)
def update(self, request, *args, **kwargs):
instance = self.get_object()
instance.name = request.data.get("name")
instance.save()
serializer = self.get_serializer(instance)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
return Response(serializer.data)
Take note that you're overriding the UpdateModelMixin and you might need to change the above code a little bit to get it right.
If you use class UpdateName(generics.CreateAPIView), this will only call a create() method on the serializer.
You should subclass generics.UpdateAPIView instead. And that's it.
You do not have to move your method to the view as suggested in this answer (it is basically copying/duplicating the UpdateModelMixin's update method)
For more information how serializers work regarding saving/updating see the docs here:
One other approach might be the following one:
serializer.py
class ClientNameSerializer(serializers.ModelSerializer):
class Meta:
model = ClientUser
fields = ('name',)
def update(self, instance, validated_data):
instance.name = validated_data.get('name', instance.name)
instance.save()
return instance
views.py
class UpdateName(generics.UpdateAPIView):
queryset = ClientUser.objects.all()
serializer_class = ClientNameSerializer
permission_classes = (permissions.IsAuthenticated,)
def update(self, request, *args, **kwargs):
data_to_change = {'name': request.data.get("name")}
# Partial update of the data
serializer = self.serializer_class(request.user, data=data_to_change, partial=True)
if serializer.is_valid():
self.perform_update(serializer)
return Response(serializer.data)