Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django, how can I generate csrf token when not using templates

I'm writing pages in my own code, not using Django templates. Because I'm overloaded on new things to learn and trying to get this done.

Now I had some easy cases with templates, and {% csrf_token %} worked just fine. But they used render() and a template.

I have a bunch of custom HTML I can't immediately figure out how to put in a template, so I can't use render(). Instead, I return HttpResponse() applied to my page, and that does not deal with {% csrf_token %}.

How do I get that <input> element into the form part of my page? I'm willing to generate the form from a template, but not the rest of the page.

like image 971
4dummies Avatar asked Feb 03 '18 23:02

4dummies


People also ask

How does Django generate CSRF token?

The CSRF token is like an alphanumeric code or random secret value that's peculiar to that particular site. Hence, no other site has the same code. In Django, the token is set by CsrfViewMiddleware in the settings.py file. A hidden form field with a csrfmiddlewaretoken field is present in all outgoing requests.

How does the CSRF token get generated?

A CSRF token is a unique, secret, unpredictable value that is generated by the server-side application and transmitted to the client in such a way that it is included in a subsequent HTTP request made by the client.

Is CSRF token necessary Django?

If you're using SessionAuthentication you'll need to include valid CSRF tokens for any POST , PUT , PATCH or DELETE operations. In order to make AJAX requests, you need to include CSRF token in the HTTP header, as described in the Django documentation.


1 Answers

You can get the CSRF token outside of a Django template by calling the appropriate function from the CSRF middleware:

from django.middleware.csrf import get_token

def your_view(request):
    csrf_token = get_token(request)
    csrf_token_html = '<input type="hidden" name="csrfmiddlewaretoken" value="{}" />'.format(csrf_token)

One thing to keep in mind is that Django templates don't really care about what you pass into them. They only touch content between {% ... %} and {{ ... }} tags. If your template is just static HTML, the Django template engine will not touch it at all and it'll be as if you served it as a normal file.

like image 166
Blender Avatar answered Oct 19 '22 03:10

Blender