[Answered ]-Convert POST to PUT with Tastypie

1👍

I had a similar problem on user creation where I wasn’t able to check if the record already existed. I ended up creating a custom validation method which validated if the user didn’t exist in which case post would work fine. If the user did exist I updated the record from the validation method. The api still returns a 400 response but the record is updated. It feels a bit hacky but…

👤Cathal

1👍

from tastypie.validation import Validation

class MyValidation(Validation):

    def is_valid(self, bundle, request=None):
        errors = {}
        #if this dict is empty validation passes. 

        my_foo = foo.objects.filter(id=1)
        if not len(my_foo) == 0: #if object exists      
            foo[0].foo = 'bar'    #so existing object updated
            errors['status'] = 'object updated'  #this will be returned in the api response

        return errors 

    #so errors is empty if object does not exist and validation passes. Otherwise object
    #updated and response notifies you of this

class FooResource(ModelResource):
    class Meta:
        queryset = Foo.objects.all() # "id" = models.AutoField(primary_key=True)
        validation = MyValidation()
👤Cathal

0👍

With Cathal’s recommendation I was able to utilize a validation function to update the records I needed. While this does not return a valid code… it works.

from tastypie.validation import Validation
import string # wrapping in int() doesn't work

class Validator(Validation): 
    def __init__(self,**kwargs):
        pass

    def is_valid(self,bundle,request=None):
        if string.atoi(bundle.data['id']) in Foo.objects.values_list('id',flat=True):
                # ... update code here
        else:
            return {}

Make sure you specify the validation = Validator() in the ModelResource meta.

Leave a comment