Django REST Framework PATCH not working in required fields

We are creating an API that should allow the user to update the record. In many cases, for example, when updating a status or changing a name, only one field changes. This seems like a suitable use case for a PATCH request. As I understand it, this is a "partial" update.

We implemented the Django REST Framework and ran into this problem. For a record such as "AccountUser", I want to change the name field, so I will send the following request: PATCH / api / users / 1 / HTTP / 1.1 Host: localhost X-CSRFToken: 111122223333444455556666 Content-Type: application / json; charset = UTF-8 Cache-Control: no-cache

{ "fullname": "John Doe" } 

The record obviously has other attributes, including a couple of related fields, such as the “account”, which is required for the new record. When sending a request, the response is an error 400 with the following body: {"account": ["This field is required." ]} The serializer for the user is as follows:

 class AccountUserSerializer(serializers.ModelSerializer): account = serializers.PrimaryKeyRelatedField() class Meta: model = AccountUser fields = ('id', 'account', 'fullname', ... ) depth = 1 

And the model is as follows:

 class AccountUser(models.Model): ''' Account User''' fullname = models.CharField(max_length=200, null=True,blank=True) account = models.ForeignKey(Account, on_delete=models.PROTECT ) objects = AccountUserManager() def __unicode__(self): return self.email class Meta: db_table = 'accounts_account_user' 

Am I doing something wrong here, or is it wrong to expect him to be able to update one field on a record this way. Thank you This is a community of rock!

EDIT: Requested - AccountUserManager:

 class AccountUserManager(BaseUserManager): def create_user(self, email, account_name): username = hash_email_into_username(email) ... account = Account.objects.get(name=account_name) account_user = AccountUser(email=email,user=user,account=account) account_user.save() return account_user 
+7
python rest django django-rest-framework
source share
2 answers

It doesn't seem like your manager is filtering the user. I would advise you to use pdb and set a breakpoint in your view code and go to it to find out why it is trying to create a new record. I can guarantee that we use PATCH to completely update a partial update and send several fields at once to update without problems.

Only another thought is that you are somehow sending a value for account (e.g. null ) that causes a validation error, even if you only see an example sending the fullname field.

+1
source share

See my answer for partial updates. You can also see drf docs , and this docs

0
source share

All Articles