django-rest-framework icon indicating copy to clipboard operation
django-rest-framework copied to clipboard

perform_validation(), PATCH method, and partial=True

Open trippingtarballs opened this issue 13 years ago • 18 comments

As outlined in Issue #376, the partial=True flag is an API requirement for serializer to support PATCH. However, I think something might have been overlooked in the validation.

I have a view that inherits from, generics.RetrieveUpdateDestroyAPIView. The serializer for my view has two fields, one of which is of type, serializers.PrimaryKeyRelatedField(). The PKRF is required on a GET, but not on a PATCH. Each of my two fields has a custom validate_method() in the serializer.

When the REST code gets to function, rest_framework.serializers.BaseSerializer.perform_validation() there is no test of partial to check if the field's corresponding validate_method() should or should not be called.

As it stands, the function BaseSerializer.perform_validation() looks like this:

    def perform_validation(self, attrs):
        for field_name, field in self.fields.items():
            if field_name in self._errors:
                continue
            try:
                validate_method = getattr(self, 'validate_%s' % field_name, None)
                if validate_method:
                    source = field.source or field_name
                    attrs = validate_method(attrs, source)
            except ValidationError as err:
                self._errors[field_name] = self._errors.get(field_name, []) + list(err.messages)
        ...
        ...
        return attrs

I propose a small change to the code, as such:

    def perform_validation(self, attrs):
        for field_name, field in self.fields.items():
            if field_name in self._errors:
                continue
            try:
                validate_method = getattr(self, 'validate_%s' % field_name, None)
                if validate_method and not self.partial:
                    source = field.source or field_name
                    attrs = validate_method(attrs, source)
            except ValidationError as err:
                self._errors[field_name] = self._errors.get(field_name, []) + list(err.messages)
        ...
        ...
        return attrs

As things stand, on a PATCH, a KeyError exception is raised when my custom validate_method() is called (because the 'required' field is not in DATA).

Of course, it's quiet possible I'm overlooking something rather fundamental. Clarification on this point would be welcomed.

Many thanks.

trippingtarballs avatar Jul 01 '13 22:07 trippingtarballs

Not sure if it needs dealing with or what is the right way to do so. Does seem valid on first reading, but certainly not a simple as skipping validation on partial updates (the validation should still run if the field is present.) Would be helpful to try to slim this down to simplest possible failing test case.

lovelydinosaur avatar Jul 02 '13 06:07 lovelydinosaur

Thanks for the quick reply Tom.

You're right, we cannot simply skip all validation just because partial=True. My bad!

What about adding absent fields to the exclude list (I think that is, self.opts.exclude) if the method is PATCH? Perhaps this is not possible.

I can have a look into it now, if you like ..

trippingtarballs avatar Jul 02 '13 10:07 trippingtarballs

So, in the function, __init__() for class rest_framework.serializers.BaseSerializer the serializers' self.fields collection is built by a call to function, self.get_fields().

Perhaps, inside the logic of get_fields(), this might be a good opportunity to exclude a field if it is not present and the method is PATCH?

The second step in function, get_fields(), is to, add in the default fields. Perhaps here?

In the case where partial=False add the field to the self.fields collection, business as usual. However, when partial=True and the field is not in the self.init_data collection, don't add the field to self.fields?

trippingtarballs avatar Jul 02 '13 10:07 trippingtarballs

My initial thought (above) was to change how the list of fields is created. This soon got ugly because the list of fields is made-up from two parts (explicitly declared, and default).

Instead I considered removing fields at the very end of BaseSerializer.get_fields(). So, at the end of this function, before the return ret, I have added the following code:

        # Remove field if partial=True and not in PATCH data
        for item in ret:
            if self.partial and item not in self.init_data:
                ret.pop(item, None)

        return ret

From this self.fields will list any fields that are not included in self.init_data when partial=True. Thus, when BaseSerializer.perform_validation() is called it will not look to call custom validation on omitted fields for PATCH methods. However, BaseSerializer.perform_validation() should still call custom validation on present fields for PATCH methods.

Would you like me to write some tests for this?

With this change my code is now working (I don't get a KeyError exception when my custom validate_method() is called). I ran all the included rest_framework tests and nothing is appears to be failing.

Let me know what you think. Cheers.

trippingtarballs avatar Jul 02 '13 11:07 trippingtarballs

Scratch that. All the tests don't pass. They did pass with that fix on release version of REST. I've since forked & cloned (https://github.com/tomchristie/django-rest-framework.git), and the test, rest_framework.tests.test_generics.TestInstanceView.test_patch_instance_view() fails.

This makes sense. The test includes an self.assertEqual() to determine the response.data returned from the PATCH. And because the http method call, factory.patch(), includes content without the id field, the response.data does not include the id field. Thus the test fails.

From this I conclude that the proposed change in my last comment will introduce a change in behaviour to the PATCH method that will not go unnoticed.

trippingtarballs avatar Jul 02 '13 16:07 trippingtarballs

@tomchristie, clicking close was a mistake.

Do you mind if I press you for a little guidance on this? I am happy to do the coding, and write the tests too. Where I'm working we rely heavily on the REST framework. It's in my interest to help in whatever way I can. However, I don't want to spend too much energy working on a possible fix that fundamentally goes against the intended REST behaviour, and ultimately is rejected.

Please let me know what you think. Cheers.

trippingtarballs avatar Jul 06 '13 12:07 trippingtarballs

I can't make any guarantees, but it does seem like a valid issue. The best place to start would be writing a failing test. If you can submit that as a pull request that's a really useful first pass. Once that's done we can discuss possible fixes. I guess it's probably just a case of skipping the validate_method if partial is true and the field is not present.

lovelydinosaur avatar Jul 07 '13 04:07 lovelydinosaur

@rbose85 - I'm confused as to what the current status of this ticket is - it looks like you've submitted a failing test which has now been merged (so presumably the test is now passing). Do you know if we're good to close this issue?

lovelydinosaur avatar Sep 11 '13 10:09 lovelydinosaur

Yes. All looks good to me. Sorry for not having kept a closer eye on this.

trippingtarballs avatar Sep 13 '13 12:09 trippingtarballs

Yes. All looks good to me.

Great, glad to hear it :)

lovelydinosaur avatar Sep 13 '13 12:09 lovelydinosaur

@rbose85 @tomchristie Hi guys, I am having the same issue. If I understand the conversation between you guys correctly, the failing test case written by rbose85 is now passing, which means this issue is fixed in the master. I, however, don't see a reference to the PR or commit that has fixed the issue. Can you please add reference to the fix? Thanks.

tamakisquare avatar Sep 14 '13 03:09 tamakisquare

@tomchristie I have just updated to the latest release v2.3.8 and I see this issue is still there. I can help with fixing/testing the issue. But before that, I need to know where we are on the issue. Please let me know.

tamakisquare avatar Sep 14 '13 03:09 tamakisquare

Hi @tamakisquare. There's no more information than is currently on this ticket. There's a PR #973 referenced with a status of merged against it but doesn't have any commits against it(??). This is a long ticket so I'd suggest to help progress it it needs someone to concisely summarise the issue, then submit a failing test case (and of course ideally also a fix)

lovelydinosaur avatar Sep 14 '13 06:09 lovelydinosaur

@tomchristie - No wonder I got so confused. Ok, leave this to me then. I'll come up with a failing test case after this weekend. Should I open up another ticket to concisely summarize the issue?

tamakisquare avatar Sep 14 '13 18:09 tamakisquare

@tomchristie - You can find the test case here PR 1112

tamakisquare avatar Sep 16 '13 05:09 tamakisquare

Any updates on this? I just ran into what appears to be this issue.

kevin-brown avatar Oct 15 '13 21:10 kevin-brown

@kevin-brown - I have just included my fix to PR https://github.com/tomchristie/django-rest-framework/pull/1112. See if it helps you.

tamakisquare avatar Oct 16 '13 00:10 tamakisquare

from django.db import models
from django.core.validators import RegexValidator

class NUser(models.Model):
    color = models.CharField(max_length=6, default=get_random_color,
                             validators=[RegexValidator(regex='^[A-F0-9]{6}$', message='No color', code='nocolor')])
from rest_framework import serializers

import foo.models as models

class NUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.NUser
        fields = ('color')
from rest_framework.response import Response
from rest_framework import viewsets, status

class UserViewSet(viewsets.ViewSet):
    def partial_update(self, request, pk=None):
        serialized = NUserSerializer(request.user, data=request.DATA, partial=True)
        return Response(status=status.HTTP_202_ACCEPTED)

The RegexValidator isn't enforced when PATCHing the UserViewSet, but it is just fine when using the same Model in the django admin. This means that I can supply values like zzaa which will be written to the database as a valid color.

Am I doing something wrong here?

luto avatar Jul 08 '14 11:07 luto