Search code examples
djangodjango-csrf

how to use django_csrf for mobile application


I am writing a mobile application for a django website. i understand that every form in django has a CSRF token key for protection. when use browser to navigate the site, the server render a key for the user.

What i am confused is for mobile application, we dont need view the presetation layer from the site. I just wanna do a HTTP post to send data. I know i can use csrf_exempt to disable the csrf for that form. or i can make another view to render the csrf token for me, but this way i need extra parsing and http request. so is there a nicer way to do it?

Thanks for your time


Solution

  • If your mobile app is rendering a template you can add {% csrf_token %} into the template that renders the form. If you're not using a form and instead just posting data you can create the token as above and then simply post it's value with the data. And if you're not using a template to create the mobile app's markup well then use csrf_exempt (if say you're just posting data to the server periodically).

    Obviously there has to be a view to process the posted data, but even if you're using a generic view for that you could still wrap that view (in your urls.py for example) and gain the use of csrf_exempt