0
votes

I have seen a number of forums and posts but still couldn't get the handle of it. Here in django doc, it says

The CSRF middleware is activated by default in the MIDDLEWARE setting. If you override that setting, remember that 'django.middleware.csrf.CsrfViewMiddleware' should come before any view > middleware that assume that CSRF attacks have been dealt with.

If you disabled it, which is not recommended, you can use csrf_protect() on particular views you want to protect (see below).

In any template that uses a POST form, use the csrf_token tag inside the > element if the form is for an internal URL, e.g.:

form action {% csrf_token %}

Based on that, in my html template I did simply:

 <form id='frm' name='frm' method="post" action="{% url 'gettip' %}" >
        {% csrf_token %}

 <input type="text" name="tipid" name="tipid">
 <input type="submit" value="Get Tip Value"/>
</form>

I expected the CSRF_token to create the hidden element since the middleware is already loaded. I see no element in the form and I get CSRF error.

The form is not associated with any model. I haven't used forms.py either. My current view is simply to output something:

def gettip(request):

    if request.POST:
         return HttpResponse('You requested a tip')
   
#from a weblink, i was told to add the following but it made no difference   
context = {}
return render_to_response('tip.html',context, context_instance=RequestContext(request))

The error I am getting is obviously CSRF missing cos the hidden element is not there at all.

I am migrating from PHP and this is giving me a hard time. Though my form is not for login purposes, I couldn't get this one to work either for the same error. I am on django 1.10 and just want to get a positive response when form is submitted.

1
Is that gettip the view that is rendering the template that form is on? If not, please show the one that is.Daniel Roseman
context_instance was removed from render_to_response in Django 1.10, so that view shouldn't work at all.Alasdair

1 Answers

0
votes

Don't use render_to_response, it's obsolete. Use render instead.

from django.shortcuts import render

def gettip(request):

   if request.POST:
       return HttpResponse('You requested a tip')

   context = {}
   return render(request, 'tip.html', context)

If the template containing the form is rendered by another view, you'll have to fix that view as well.