0

I have a problem about django csrf. Here is my view code.

    if request.user.is_authenticated():
      res = {"is_authenticated": "true"}
    else:
      res = {}

    return render_to_response('app/index.html', res, context_instance=RequestContext(request))
Woody
  • 11
  • 1
  • Can you be more precise where are you getting error? Normally it comes when you are missing `csrf_token` tag in your form. – Netro Feb 17 '16 at 04:27
  • Possible duplicate of [Django: CSRF token missing or incorrect](http://stackoverflow.com/questions/8321217/django-csrf-token-missing-or-incorrect) – Selcuk Feb 17 '16 at 04:58

2 Answers2

0

Check if the CsrfViewMiddleware is added in your MIDDLEWARE_CLASSES tuple in settings.py and then you can simply do {% csrf_token %} inside the template to get the token.

settings.py

MIDDLEWARE_CLASSES = (
    ...
    ...
    'django.middleware.csrf.CsrfViewMiddleware',
    ...
    ...
)

app/index.html

<form action="" method="post">{% csrf_token %}


Refer documentation for more info.

Parag Tyagi
  • 8,780
  • 3
  • 42
  • 47
-2

In your views.py use @csrf_exempt decorator above your function, for that need to import this decorator first like this

from django.views.decorators.csrf import csrf_exempt

then use it in your view function for eg.

@csrf_exempt
def sample_func(request):
    if request.user.is_authenticated():
        res = {"is_authenticated": "true"}
    else:
        res = {}
    return render_to_response('app/index.html', res, context_instance=RequestContext(request))

And after that in your index.html file call this decorator in form tag like this

<form method="" action="">
{% csrf_token %}

.......

</form>
  • No. You should not give advice like this. CSRF protection is there for a reason; randomly disabling it is almost always the wrong thing to do. – Daniel Roseman Feb 17 '16 at 09:20