CSRF verification failed. Request aborted.

780 views
Skip to first unread message

JJ Zolper

unread,
Jul 9, 2012, 9:53:12 PM7/9/12
to django...@googlegroups.com
Here is the error I received with debug set to true for Django:

Forbidden (403)

CSRF verification failed. Request aborted.

Help

Reason given for failure:

    CSRF token missing or incorrect.
    

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

  • The view function uses RequestContext for the template, instead of Context.
  • In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
  • If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.

You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.


I'm wondering if this is caused because I don't have a redirect page for my 'POST' HTML submit.

Now my code...

URLCONF:

from django.conf.urls.defaults import patterns, include, url

from MadTrak.manageabout.views import about, about_form


    # Uncomment the next two lines to enable the admin:

from django.contrib import admin

admin.autodiscover()


urlpatterns = patterns('',


    (r'^about_form/', about_form),

    (r'^about/', about),


    # Examples:

    # url(r'^$', 'MadTrak.views.home', name='home'),

    # url(r'^MadTrak/', include('MadTrak.foo.urls')),


## url(r'^$', 'MadTrak.views.home', name='home'), with a view named home

## url(r'^listen/', 'MadTrak.views.home', name='home'), with a view named home

## url(r'^home/', 'MadTrak.views.home', name='home'), with a view named home


    # Uncomment the admin/doc line below to enable admin documentation:

    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),


    # Uncomment the next line to enable the admin:

    url(r'^admin/', include(admin.site.urls)),

)


views.py in my manageabout app:

from django.http import HttpResponseRedirect

from django.shortcuts import render_to_response

from MadTrak.manageabout.models import AboutMadtrak


def about_form(request):

    return render_to_response('about_form.html')


def about(request):

    if request.method == 'POST':

       # do_something_for_post()

    return HttpResponseRedirect('about.html')

    elif request.method == 'GET':

        return render_to_response('/')

    else:

        raise Http404()


model where i tried to set up my database to recieve the information posted:

from django.db import models


class AboutMadtrak(models.Model):

    name = models.CharField(max_length=30)

    title = models.CharField(max_length=60)

    bio = models.CharField(max_length=200)

    website = models.URLField()


    def __unicode__(self):

       return self.nam


my template for the about form submission:


<html>

<title>About-Form</title>

<head>


</head>

<body>


MadTrak About Page, Yo!


<p></p>


<form action="/about_form/" method="post">

{% csrf_token %}

<p>Name: <input type="text" name="name" value=""></p>

<p>Title: <input type="text" name="title" value=""></p>

        <p>Bio: <textarea name="bio" rows="10" cols="50"></textarea></p>

<p>Website: <input type="text" name="website" value=""></p>

<input type="submit" value="Submit">

</form>


</body>

</html>




In conclusion I am fairly new to even 'POST' and 'GET' operations so I apologize haha. Anyways, I see the CSRF error and I was confused because i recall that having to do with security? An open operation from submission to a redirect page? I'm not sure.

All I wanted to accomplish was to be able to post the data in that template and see the result in my in my MadTrak database. That's it. Just see the data as an item in my database. Any help is welcomed as I try to iron this out!

Cheers to all the Django developers out there!

JJ Zolper

Сергей Фурсов

unread,
Jul 10, 2012, 2:36:17 AM7/10/12
to django...@googlegroups.com
as described in error message your view  function have to use RequestContext for the template, instead of Context. 
your view should looks like

def about(request):
    if request.method == 'POST':
        return HttpResponseRedirect('/about/')
    elif request.method == 'GET':
        return render_to_response('about.html', context_instance=RequestContext(request))
    else:
        raise Http404()

note that you redirect (HttpResponseRedirect) to url, but render (render_to_response) template with context

also I changed action for form in tempalte to /about/ to handle POST and GET requests in same view

hope this helps

2012/7/10 JJ Zolper <codin...@gmail.com>

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/DChOPlS2aAsJ.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

Message has been deleted
Message has been deleted
Message has been deleted

Sergiy Khohlov

unread,
Jul 11, 2012, 8:31:20 AM7/11/12
to django...@googlegroups.com
problem in view also :

def about(request):
if request.method == 'POST':
return HttpResponseRedirect('/about/')
elif request.method == 'GET':
return render_to_response('about.html',
context_instance=RequestContext(request))
else:
raise Http404()

this one should be converted to :

def about(request):
if request.method == 'POST':
return HttpResponseRedirect('/about/')
elif request.method == 'GET':
protectedbycsrf= {}
protectedbycsrf.update(csrf(request))
return render_to_response('about.html',
context_instance=RequestContext(protectedbycsrf))
else:
raise Http404()



2012/7/11 Сергей Фурсов <geys...@gmail.com>:
> oops)
>
>
> 2012/7/11 Сергей Фурсов <geys...@gmail.com>
>>
>> Some notes about your models:
>> 1. why do you create id field manually? Django will do it for you ;)
>> 2. why do you explicitly set db_table and db_column? Do you have some
>> legacy database? If not, django will do it for you ;)
>> 3. move your vision from tables to objects
>> 4. call your models in CamelCase notation and in singular form
>> 5. try to understand related_name parameter
>> https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name
>>
>> in my opinion your models should looks like:
>> from django.db import models
>>
>> class Owner(models.Model):
>> num = models.IntegerField()
>>
>> def __unicode__(self):
>> return unicode(self.num)
>>
>>
>> class Vehicle(models.Model):
>> plate = models.CharField(max_length=80, unique=True)
>> owner1 = models.ForeignKey('Owner', null=True,
>> related_name='vehicles1', blank=True)
>> owner2 = models.ForeignKey('Owner', null=True,
>> related_name='vehicles2', blank=True)
>>
>> def __unicode__(self):
>> return self.plate
>>
>>
>> class WebRequest(models.Model):
>> owner = models.ForeignKey('Owner')
>> vehicle1 = models.ForeignKey(Vehicle, related_name='web_requests1')
>> vehicle2 = models.ForeignKey(Vehicle, null=True,
>> related_name='web_requests2', blank=True)
>>
>>
>>
>> 2012/7/11 Сергей Фурсов <geys...@gmail.com>
>>>
>>> Ok, I tried your code, just added in models.py fake owners model to
>>> correct foreign key
>>>
>>> class Owners(models.Model):
>>> num = models.IntegerField()
>>>
>>> def __unicode__(self):
>>> return unicode(self.num)
>>>
>>> and create views.py with three lines of code:
>>>
>>> def page(request):
>>> form = WebrequestsForm(own_id=1)
>>> return render_to_response('page.html', {'form': form})
>>>
>>> and it works!
>>> May be problem in your views.py?
>>>
>>>
>>> 2012/7/10 Сергей Фурсов <geys...@gmail.com>

JJ Zolper

unread,
Jul 11, 2012, 11:16:27 AM7/11/12
to django...@googlegroups.com
I apologize for not responding sooner!

This line:

        return render_to_response('about.html', context_instance=RequestContext(request)) 

helped immensely! so in order for the render response method to work it has to have some sort of data/context of data passed along with it? I'm still trying to think about that.

Also if I add:

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

the csrf token right after my form it seems to work like a charm!

I've actually started a new thread under:  Form 'POST' to a database 

because I'm trying to understand exactly how once the html form using POST is submitted how that propagates through and into my database.

I think that's the real issue here. This CSRF issue really not that important currently because it's just a security/setting issue. It just protects againist the issue of data not coming from the context of the request and from elsewhere on the internet! Not good but not a major priority for me right now.

Thanks,

JJ

2012/7/10 JJ Zolper <codin...@gmail.com>
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.

JJ Zolper

unread,
Jul 11, 2012, 11:19:37 AM7/11/12
to django...@googlegroups.com
Yep it's a problem with my views.py and my template or html page.

My html page needed the csrf token tag: {% csrf_token %}

and my view needed:         return render_to_response('about.html', context_instance=RequestContext(request)) 

so thanks for the help!!!

On Wednesday, July 11, 2012 7:58:54 AM UTC-4, Sergey Fursov wrote:
Ok, I tried your code, just added in models.py fake owners model to correct foreign key

class Owners(models.Model):
    num = models.IntegerField()

    def __unicode__(self):
        return unicode(self.num)

and create views.py with three lines of code:

def page(request):
    form = WebrequestsForm(own_id=1)
    return render_to_response('page.html', {'form': form})

and it works! 
May be problem in your views.py?


2012/7/10 Сергей Фурсов <geys...@gmail.com>
as described in error message your view  function have to use RequestContext for the template, instead of Context. 

2012/7/10 JJ Zolper <codin...@gmail.com>
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.

JJ Zolper

unread,
Jul 11, 2012, 11:22:20 AM7/11/12
to django...@googlegroups.com
1. I don't think I set my id field just name title bio and website.
2. I don't set those two values.
3. not sure..
4. not sure...

I believe you corrected yourself as this post doesn't seem relevant. Not a problem!


On Wednesday, July 11, 2012 8:11:46 AM UTC-4, Sergey Fursov wrote:
Some notes about your models:
1. why do you create id field manually? Django will do it for you ;)
2. why do you explicitly set db_table and db_column? Do you have some legacy database? If not, django will do it for you ;)
3. move your vision from tables to objects
4. call your models in CamelCase notation and in singular form

in my opinion your models should looks like:
from django.db import models

class Owner(models.Model):
    num = models.IntegerField()

    def __unicode__(self):
        return unicode(self.num)


class Vehicle(models.Model):
    plate = models.CharField(max_length=80, unique=True)
    owner1 = models.ForeignKey('Owner', null=True, related_name='vehicles1', blank=True)
    owner2 = models.ForeignKey('Owner', null=True, related_name='vehicles2', blank=True)

    def __unicode__(self):
        return self.plate


class WebRequest(models.Model):
    owner = models.ForeignKey('Owner')
    vehicle1 = models.ForeignKey(Vehicle, related_name='web_requests1')
    vehicle2 = models.ForeignKey(Vehicle, null=True, related_name='web_requests2', blank=True)



2012/7/11 Сергей Фурсов <geys...@gmail.com>
Ok, I tried your code, just added in models.py fake owners model to correct foreign key

class Owners(models.Model):
    num = models.IntegerField()

    def __unicode__(self):
        return unicode(self.num)

and create views.py with three lines of code:

def page(request):
    form = WebrequestsForm(own_id=1)
    return render_to_response('page.html', {'form': form})

and it works! 
May be problem in your views.py?


2012/7/10 Сергей Фурсов <geys...@gmail.com>
as described in error message your view  function have to use RequestContext for the template, instead of Context. 

2012/7/10 JJ Zolper <codin...@gmail.com>
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.

JJ Zolper

unread,
Jul 11, 2012, 11:24:23 AM7/11/12
to django...@googlegroups.com
Thanks so much for the tip!

I had part of the solution there from our other friend but I will add that extra protection when I can!

Are you familiar with CSRF? And your solution what the issue you fix is?

Any other insight into the reason for the code would be great!

Thanks again,

JJ
>>>>> For more options, visit this group at
>>>>> http://groups.google.com/group/django-users?hl=en.
>>>>
>>>>
>>>
>>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django...@googlegroups.com.
> To unsubscribe from this group, send email to
Reply all
Reply to author
Forward
0 new messages