Search code examples
pythondjangoformscsrf

Using GET in a Django Form


I have a question regarding Django Forms and GET

I have a form to download student scores in CSV format. The fields are name and year so I have a forms.py

StudentDownloadForm(forms.Form):
  name=forms.CharField()
  year = forms.CharField()

And I want to use this form in the template.html with

context={'student_form' : StudentDownloadForm(),}

<form action ="" method="GET">
  {% csrf_token %}{{ student_form|crispy }}
<input type="submit" value="Query"/>
</form>

So my questions are as follows:

  • If I use the method="GET" then the csrf token is visible in the URL, which is a security issue
  • Can I then use the method="POST" instead?
  • Alternatively, can I remove the csrf token in the form?

Solution

  • According to Django documentation (Cross Site Request Forgery protection):

    For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or TRACE, a CSRF cookie must be present, and the ‘csrfmiddlewaretoken’ field must be present and correct. If it isn’t, the user will get a 403 error.

    And:

    It deliberately ignores GET requests (and other requests that are defined as ‘safe’ by RFC 2616). These requests ought never to have any potentially dangerous side effects , and so a CSRF attack with a GET request ought to be harmless. RFC 2616 defines POST, PUT and DELETE as ‘unsafe’, and all other methods are assumed to be unsafe, for maximum protection.

    So, you can omit CSRF token for GET requiests