Buğra İşgüzar
Buğra İşgüzar

Reputation: 37

django CSRF verification failed. Request aborted

I create form on django project. I have a error csrf failed.

My wievs.py file:

def durum(request): 
    if request.method == "POST":
        adi = request.POST.get('durum')
        db = sql.connect("/usr/connect.db")
        im = db.cursor()
        db.execute("INSERT INTO durum VALUES ("+str(adi)+")")
        db.commit()
        asd = "Durum mesajı '"+str(adi)+"' olarak değiştirildi."
        return render(request, asd, {})
    else:
        BASE = os.path.dirname(os.path.abspath(__file__))
    return HttpResponse(open(os.path.join(BASE, "html/durum.html")).read())

My urls.py file:

url(r'^durum/', db.durum),

My html file:

<form action="/durum" method="post">
{% csrf_token %}
<table>
    <tr><th>Durum Mesajı:</th><td><input type="text" name="durum"/></td></tr>
     <tr><th></th><td><input type="submit" value="Ekle"/></td></tr>
</table>

Upvotes: 0

Views: 481

Answers (2)

Andrii Rusanov
Andrii Rusanov

Reputation: 4606

You should use django templates and RequestContext. The very fast way to check it: in your app folder create following directory structure:

1.templates/myapp_name Use name of the app, not project name!

  1. Create file my_template.html

  2. in your view add import:

    from django.shortcuts import render

add replace your return with

return render('myapp_name/my_template.html')

Read more about configure template directory: Django template Path

Read more about render: https://docs.djangoproject.com/en/1.7/intro/tutorial03/#a-shortcut-render

Note: It's better to use django forms instead of your way: https://docs.djangoproject.com/en/1.7/topics/forms/ and class based views instead of functions(they may looks complicated by believe me - they are really awesome: https://docs.djangoproject.com/en/1.7/topics/class-based-views/

Also try do not use hardcoded urls, use https://docs.djangoproject.com/en/1.7/topics/http/urls/#reverse-resolution-of-urls instead It will done all work for you!

Upvotes: 1

Alvaro
Alvaro

Reputation: 12037

You should follow the "django-way" to render your template. The way your view works is sending the template as plain html instead of proccessing it. Try it this way:

def durum(request): 
if request.method == "POST":
    adi = request.POST.get('durum')
    db = sql.connect("/usr/connect.db")
    im = db.cursor()
    db.execute("INSERT INTO durum VALUES ("+str(adi)+")")
    db.commit()
    asd = "Durum mesajı '"+str(adi)+"' olarak değiştirildi."
    return render(request, asd, {})
else:
    return render('your_template_name.html', context_instance=RequestContext(request))

This way, django will proccess your template and render a correct csrf_token. I strongly suggest you follow the tutorial on djangoproject.com and make use of the ORM as well

Upvotes: 2

Related Questions