0

I'm using Djangos CSRF-Token the way it's mostly described on the internet:

MyFormPage.html

<form method="POST">  
        {% csrf_token %}  
        {{ form.as_p }}  
</form>

But I wonder - is there a way to include it somehow directly in the forms.py?

Qohelet
  • 1,459
  • 4
  • 24
  • 41

1 Answers1

1

I don't know if this is a good practice or not, but you can do something like:

from django.middleware import csrf

class SomeForm(forms.Form):
    csrfmiddlewaretoken = forms.CharField(widget=forms.HiddenInput(), initial=csrf._get_new_csrf_token())

The rendered input field will be:

<input type="hidden" name="csrfmiddlewaretoken" value="Hsw4uH5jbioQhaWrgAtGgEVp5GbnXIrayuvTqbbABaSxPbGJqksEIxVI4zJW8VVj" id="id_csrfmiddlewaretoken">
Nalin Dobhal
  • 2,292
  • 2
  • 10
  • 20