I am trying to use Piston to provide REST support to Django. I have implemented my handlers as per the documentation provided . The problem is that i can "read" and "delete" my resource but i cannot "create" or "update". Each time i hit the relevant api i get a 400 Bad request Error.
I have extended the Resource class for csrf by using this commonly available code snippet:
class CsrfExemptResource(Resource):
"""A Custom Resource that is csrf exempt"""
def __init__(self, handler, authentication=None):
super(CsrfExemptResource, self).__init__(handler, authentication)
self.csrf_exempt = getattr(self.handler, 'csrf_exempt', True)
My class (code snippet) looks like this:
user_resource = CsrfExemptResource(User)
class User(BaseHandler):
allowed_methods = ('GET', 'POST', 'PUT', 'DELETE')
@require_extended
def create(self, request):
email = request.GET['email']
password = request.GET['password']
phoneNumber = request.GET['phoneNumber']
firstName = request.GET['firstName']
lastName = request.GET['lastName']
self.createNewUser(self, email,password,phoneNumber,firstName,lastName)
return rc.CREATED
Please let me know how can i get the create method to work using the POST operation?
I thought Eric's solution worked the best but then ran into problems when saving things in admin. This tweak seems to fix it if anyone else comes across it:
In utils.py, change this.
https://bitbucket.org/jespern/django-piston/issue/87/split-charset-encoding-form-content-type
This is happening because Piston doesn't like the fact that ExtJS is putting "charset=UTF-8" in the content-type of the header.
Easily fixed by adding some middleware to make the content-type a bit more Piston friendly, create a file called middleware.py in your application base directory:
Then simply include this middleware in your settings.py:
Proposed solutions still did not work for me (django 1.2.3/piston 0.2.2) so I've tweaked joekrell solution and this finally works (I'm only using POST and PUT, but presumably you can add other verbs to the list):
with:
I haven't noticed any side-effect, but I can't promise it's bullet-proof.
We had a resource that was simply updating a timestamp based on the request credentials and PUT. It turns out that Piston does not like PUT without a payload. Adding an empty string payload '' fixed it.
A quick Google search indicates that other systems like Apache may not like PUT without a payload, as well.
I have combined some of what other people have said, and added support for any content type, json for instance...