I have a custom serializer like this--
class customSerializers(serializers.Serializer):
token = serializers.CharField(max_length=12)
And I have a model like this
class UserToken(models.Model):
user = models.ForeignKey(User)
token = models.CharField(max_length=12)
Now I want to validate my customSerializers token field. The token value has to exists in the UserToken model and belongs to the current user.
** I Don't want to use model serializer.
You should pass user to serializer, then implement validation on the field:
class CustomSerializer(serializers.Serializer):
token = serializers.CharField(max_length=12)
def validate_token(self, value):
user_id = self.context.get('user_id')
return UserToken.objects.filter(user__id=user_id, token=value).exists()
in your view:
serializer = CustomSerializer(... , context={'user_id': request.user.id})
if serializer.is_valid():
...
Related
I want to pass user_id from view to serializer
I have model Answer
class Answer(models.Model) :
text = models.CharField(max_length=500)
question_id = models.CharField(max_length=25)
user_id = models.CharField(max_length=25, default=1)
This is my Serializer
class CreateAnswer(generics.CreateAPIView) :
def get_serializer_context(self):
context = super().get_serializer_context()
context["id"] = self.request.user.id
return context
serializer_class = AnswerQuestionSerializer
queryset = Answer.objects.all()
What I need to write in my view to take user_id and create model with this user_id ?
You can override the perform_create method & pass the user_id field to save method of the serializer.
class CreateAnswerView(generics.CreateAPIView) :
serializer_class = AnswerQuestionSerializer
def perform_create(self, serializer):
serializer.save(user_id=self.request.user.id)
You can use serializers.Hiddenfield to get current user in serializer class
https://www.django-rest-framework.org/api-guide/fields/#hiddenfield
There are multiple ways to do this task. One of them is to override create in your serializer.
Following is the code snippet:
class BlogSerializer(serializers.Serializer):
def create(self, validated_data):
user = self.context['request'].user
blog = Blog.objects.create(
user=user,
**validated_data
)
return blog
Explanation: A context is passed to the serializer which contains the request by default. So you can access the user easily with self.context['request'].user
I have following serializer:
class AdminSerializer(serializers.Serializer):
def validate(self, data):
user = data.get("user_pk")
total_licenses = data.get("total_licenses")
#here i do some validation with the vars
But my data is always empty. This is part of my view
serializer_class = self.get_serializer_class()
serializer = serializer_class(
data=self.request.data,
)
serializer.is_valid(raise_exception=True)
This is my unit test request:
response = self.client.patch(
url,
data={"user_pk": self.user.pk, "total_licenses": 3},
)
Why is my 'data' always empty?
You have to explicitly specify fields in your serializer:
class AdminSerializer(serializers.Serializer):
user_pk = serializers.IntegerField()
total_licenses = serializers.IntegerField()
def validate(self, data):
...
You need to call serializer.save() before you can access .data attribute on a serializer. Otherwise, you can access .validated_data attribute on your serializer
Context
For a specific use case I need to be able to update a single field of my Visitor model using a GET request instead of a PATCH request.
My relevant Visitor model looks like this:
# models.py
class Visitor(models.Model):
visitor_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True)
customers = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customer_visitors')
audiences = models.ManyToManyField(Audience, related_name='audience_visitors')
cid = models.CharField(max_length=255, unique=True)
uid = models.CharField(max_length=255)
cup = JSONField(null=True)
def __str__(self):
return self.cid
class Meta:
db_table = 'visitor'
I am using a straightforward serializer like this:
# serializers.py
class VisitorSerializer(serializers.ModelSerializer):
class Meta:
model = Visitor
fields = ('customers', 'cid', 'uid', 'cup')
I am able to update just the cup field for a specific Visitor which is looked up using the unique cid field with a PATCH like this:
# views.py
class VisitorViewSet(viewsets.ModelViewSet):
serializer_class = VisitorSerializer
queryset = Visitor.objects.all()
lookup_field = 'cid'
def list(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.serializer_class(instance, data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
Problem
The problem is that I am unable to update the cup field of a Visitor based on a given unique cid field using a GET request.
What I tried
As this answer by Uri Shalit suggested, I tried to override get_serializer() inside my VisitorViewSet and tried to use it in list() like this:
# views.py
class VisitorViewSet(viewsets.ModelViewSet):
serializer_class = VisitorSerializer
queryset = Visitor.objects.all()
lookup_field = 'cid'
def get_serializer(self, *args, **kwargs):
kwargs['partial'] = True
return super(VisitorViewSet, self).get_serializer(*args, **kwargs)
def list(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
However, updating just the cup field of a specific Visitor based on the cid field works with a PATCH request but does not update said field with a GET request. There is no error either.
Expected behaviour
Making a GET request which contains cid to identify a Visitor and cup with data that needs to be updated for the given Visitor. I know it breaks REST principles but for this use case I need to do this partial update using a GET request instead of a PATCH request.
Any help or pointers in the right direction would be much appreciated!
Add a classmethod in your model.
class Visitor(models.Model):
visitor_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True)
customers = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customer_visitors')
audiences = models.ManyToManyField(Audience, related_name='audience_visitors')
cid = models.CharField(max_length=255, unique=True)
uid = models.CharField(max_length=255)
cup = JSONField(null=True)
def __str__(self):
return self.cid
class Meta:
db_table = 'visitor'
#classmethod
def update_cup(cls, cid, cup_new):
instance = cls.objects.get(cid=cid)
instance.cup = new_cup
instance.save()
In ModelViewSet override the get_queryset method, see below:
IDK how u calc new_cup I guess u get it as a queryparam
def get_queryset(self):
queryset = Visitor.objects.all()
cup_new = self.request.query_params.get('cup_new', None)
cid = self.request.query_params.get('cid', None)
[obj.update_cup(obj.cid, cup_new) for obj in queryset if obj.cid == cid]
return queryset
I recommend using an api_view to accomplish what you want. api_view is an annotation provided by the rest framework so it should be available already in your case.
#api_view(["GET"])
def update_function(request):
query_params = request.GET # Getting the parameters from request
cid = query_params["cid"]
cup = query_params["cup"]
visitor = Visitor.objects.get(cid = cid)
visitor["cup"] = cup
serializer = VisitorSerializer(data = visitor, partial=True)
if serializer.is_valid():
serializer.save()
else:
print(serializer.errors)
However I am not sure about the syntax but the approch is sufficient for your problem.
Make sure to add the function to urls.py and have a look to the documentation to get better information than mine Api Views. But dont expect it to have information about you specific problem. In your case you have to understand the api_view concept and adapt it for your needs.
I think I don't understand the problem fully. Why can't you simply override the method get_object() in your view and do custom logic in it to update the object?
def get_object(self):
obj = super().get_object()
serializer = self.get_serializer(obj, data=self.request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return obj
I'm writing a serializer to provide multiple partial updates to a django model. I'm following the example implementation that appears in the DRF api guide, reproduced below and linked here: https://www.django-rest-framework.org/api-guide/serializers/#customizing-multiple-update.
The following was retrieved from django-rest-framework documentation:
serializer.py
class BookListSerializer(serializers.ListSerializer):
def update(self, instance, validated_data):
# Maps for id->instance and id->data item.
book_mapping = {book.id: book for book in instance}
data_mapping = {item['id']: item for item in validated_data}
# Perform creations and updates.
ret = []
for book_id, data in data_mapping.items():
book = book_mapping.get(book_id, None)
if book is None:
ret.append(self.child.create(data))
else:
ret.append(self.child.update(book, data))
# Perform deletions.
for book_id, book in book_mapping.items():
if book_id not in data_mapping:
book.delete()
return ret
class BookSerializer(serializers.Serializer):
# We need to identify elements in the list using their primary key,
# so use a writable field here, rather than the default which would be read-only.
id = serializers.IntegerField()
...
class Meta:
list_serializer_class = BookListSerializer
In my code I'm getting a NotImplementedError('update() must be implemented.') in my views.py when .save() is called on the serializer that is returned.
My understanding is that the ListsSerializer overrides the .update(), so could anyone help explain why I'm getting the NotImpletmentedError?
views.py
elif request.method == 'PATCH':
data = JSONParser().parse(request)
books = Book.objects.all()
# both partial and many set to True
serializer = BookSerializer(books, data=data, partial=True, many=True)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
With the help of #luistm, I managed to solve this. Continuing with the DRF example above my implementation of the update() override in the bookSerializer class was as below.
serializer.py
class BookSerializer(serializers.Serializer):
# We need to identify elements in the list using their primary key,
# so use a writable field here, rather than the default which would be read-only.
id = serializers.IntegerField()
...
class Meta:
list_serializer_class = BookListSerializer
def update(self, instance, validated_data):
"""update the page number of the book and save"""
instance.page = validated_data.get('page', instance.page)
instance.save()
return instance
I have Foo objects that are "owned" by an Organization. I get the current Organization from the logged-in User in my request handler:
models.py:
class Organization(models.Model):
name = models.CharField(max_length=255)
class Foo(models.Model):
... some other fields ...
organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
serializers.py:
class FooSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
organization = OrganizationSerializer(read_only=True)
""" Create and return a new instance, given the validated data """
def create(self, validatedData):
return OverlayDesign.objects.create(**validatedData)
""" Update and return an existing instance, given the validated_data """
def update(self, instance, validatedData):
instance.organization = validatedData.get('organization', instance.organization)
instance.save()
return instance
views.py:
def createFoo(request):
data = JSONParser().parse(request)
# Get the organization of the logged-in user
data["organization"] = OrganizationSerializer(request.user.account.organization).data
serializer = FooSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JSONResponse(serializer.data, status=201)
return JSONErrorResponse(serializer.errors, status=400)
When I create a new Foo, I want it to be owned by the current Organization. The problem is that I don't understand why the Organization is not deserialized? No matter what I do I just get:
django.db.utils.IntegrityError: null value in column "organization_id" violates not-null constraint
How should I deliver the current Organization to the FooSerializer ?
OrganizationSerializer is set with the readonly option => you won't get anything to match the current organization.
You should take a look at : http://www.django-rest-framework.org/api-guide/relations/#primarykeyrelatedfield