Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: CSRF token missing or incorrect

The error is at location http://127.0.0.1:8000/fileupload/form.py

I have version 1.3 of django. I have tried specifying localhost:8000 as stated in someone else's question but this did not work for me. I am trying to have a file upload form but I am receiving an error that form.py does not have the CSRF token.

form.py:

class UploadFileForm(forms.Form):

    title = forms.CharField(max_length=50)
    file  = forms.FileField()

views.py:

def upload_file(request):

    c = {}
    c.update(csrf(request))

    if (not request.user.is_authenticated()) or (request.user == None):
      return HttpResponseRedirect("/?error=11")


    if request.method == 'POST':
      form = c['UploadFileForm'] = UploadFileForm(request.POST, request.FILES,  c, context_instance=RequestContext(request))

      if c['UploadFileForm'].is_valid():
        handle_uploaded_file(request.FILES['file'])
        return HttpResponseRedirect('/success/url/')

    else:
        form = c['UploadFileForm'] = UploadFileForm()
    return render_to_response('fileupload/upload.html', {'form': c['UploadFileForm']})

upload.html:

{% block main_content %}


  <form action="fileupload/form.py" enctype="multipart/form-data" method="POST">
    {% csrf_token %}
    <table>

      <tr><td>Title:</td><td><input type="text" name="title" /></td></tr>
      <tr><td>File:</td><td><input type="file" name="file" /></td></tr>
    </table>
      <input type="submit" value="Submit" class = "float_right button_input" />

  </form> 

{% endblock main_content %}

I am very stumped please tell me some things to try. Thank You

like image 980
user1072646 Avatar asked Nov 30 '11 04:11

user1072646


People also ask

What is CSRF token in Django?

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.

What does {% Csrf_token %} mean?

csrf_token. Django has a {% csrf_token %} tag that is implemented to avoid malicious attacks. It generates a token on the server-side when rendering the page and makes sure to cross-check this token for any requests coming back in. If the incoming requests do not contain the token, they are not executed.

What is Csrf_exempt in Django?

csrf_exempt (view) This decorator marks a view as being exempt from the protection ensured by the middleware. Example: from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def my_view(request): return HttpResponse('Hello world')


4 Answers

You need to pass RequestContext in render_to_response for csrf_token

For this : (views.py)

from django.template import RequestContext

...

return render_to_response('fileupload/upload.html', {'form': c['UploadFileForm']},  RequestContext(request))
# Added RequestContext

This passes the token for csrf to the template.

like image 174
Yugal Jindle Avatar answered Oct 17 '22 04:10

Yugal Jindle


It can also happen if you use @cache_page(60 * 15) decorators. If you cache a page with a form containing a CSRF token, you'll cache the CSRF token of the first user only. So it's kinda hard to debug sometimes.

More info from Django documentation

If the csrf_token template tag is used by a template (or the get_token function is called some other way), CsrfViewMiddleware will add a cookie and a Vary: Cookie header to the response. This means that the middleware will play well with the cache middleware if it is used as instructed (UpdateCacheMiddleware goes before all other middleware).

However, if you use cache decorators on individual views, the CSRF middleware will not yet have been able to set the Vary header or the CSRF cookie, and the response will be cached without either one. In this case, on any views that will require a CSRF token to be inserted you should use the django.views.decorators.csrf.csrf_protect() decorator first:

from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect

@cache_page(60 * 15)
@csrf_protect
def my_view(request):
    ...
like image 36
varren Avatar answered Oct 17 '22 06:10

varren


My answer is similar to the @Yugal Jindle's answer above.

I am using Django 1.10 and I had a similar issue, it worked for me after editing

return render_to_response(param1, param2)

to

return render(request, param1, param2)

P.S. Make sure you have the below line in your MIDDLEWARE variable in the settings.py

'django.middleware.csrf.CsrfViewMiddleware'
like image 34
Mr.A Avatar answered Oct 17 '22 05:10

Mr.A


For my case, I use AJAX to post data to my views function, then the same error happens, so the easy method to solve it is to change the data from

data:{ 'k':'v' }

To

data:{ 'k':'v' ,addcsrfmiddlewaretoken:'{{ csrf_token }}',}

because we manually add a csrf-token, so it is not missing or incorrect.

like image 1
Arthur Rees Avatar answered Oct 17 '22 04:10

Arthur Rees