Django --CSRF token missing or incorrect - python

So I am getting Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect.
I have the 'django.middleware.csrf.CsrfViewMiddleware', in my middleware_classes.
Here is my template
<form name="input" action="/login/" method="Post"> {% csrf_token %}
<input type="submit" value="Submit"></form>
Here is my view
from django.shortcuts import render_to_response
from django.core.context_processors import csrf
from django.template import RequestContext
def login(request):
csrfContext = RequestContext(request)
return render_to_response('foo.html', csrfContext)
Well I am new to Django and most web development, but I cannot seem to find the problem here. Any help would be much appreciated!
Also i have tried the method in the django documentation
c = {}
c.update(csrf(request))
# ... view code here
return render_to_response("a_template.html", c)

I had the same problem with you and i found this code that solve my problem.
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.contrib import auth
#in accounts.forms i've placed my login form with two fields, username and password
from accounts.forms import LoginForm
#csrf_exempt
def login(request):
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
user = auth.authenticate(
username=form.cleaned_data["username"],
password=form.cleaned_data["password"])
auth.login(request, user)
return HttpResponseRedirect("/")
else:
form = LoginForm()
return render(request, 'accounts/login.html', {'form':form})

Try adding the #csrf_protect decorator just before your login function.
from django.views.decorators.csrf import csrf_protect
#csrf_protect
def login(request):
csrfContext = RequestContext(request)
return render_to_response('foo.html', csrfContext)
If the form is not in foo.html then you need to add the #csrf_protect method to the view function that is generating it.

Just add this line .
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});

You should do the following:
def login(request):
context = {}
request_context = RequestContext(request)
return render_to_response('foo.html', context,
request_context=request_context)
Here are official docs for render_to_response.

go urls and add the .as_view() next to the view metho/class
ex.
ObtainAuthTokenView.as_view()

While disabling the CSRF tokens and manually getting the CSRF token value would still have worked. But, in my case the syntax was not properly structured as in html we don't worry about our script design but I think when using jinja i.e. Our templating language it matter's and yes that's how I solved my problem.

Just add this in your HTML:
{% csrf_token %}

Related

How to redirect to 'http://127.0.0.1:8000/profile/' instead of 'http://127.0.0.1:8000/accounts/login/?next=/profile/'

I'm trying to edit user profiles. The user edits a form on profile.html and when they submit it, they should be redirected back to profile.html (the same page). Even though I changed my LOGIN_REDIRECT_URL, I'm still redirecting to accounts/login (the default).
views.py
#login_required
def profile(request):
user = request.user
if request.method == "POST":
signupform = SignUpForm(data=request.POST, instance=request.user)
if signupform.is_valid():
signupform.save()
return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
return render(request, 'profile.html', "context stuff here")
settings.py
LOGIN_REDIRECT_URL = '/profile'
urls.py
url(r'^profile/$', views.profile, name='profile')
How can I successfully redirect to profile.html?
Try this replacing APPNAME with your app's name (same as the app name you declared in INSTALLED APPS section in settings.py) in the code below
return HttpResponseRedirect(reverse('APPNAME:profile'))
and don't forget to import at the top of your page
from django.urls import reverse
You use #login_required decorator but you are not logged in. So that it redirects you to the login page. If you login then it redirect to /profile.
You can do this,
#login_required
#...
if signupform.is_valid():
signupform.save()
return redirect('profile') # or 'app_name:profile' if you have app_name before your urlpatterns.
Your login_required will redirect you to settings.LOGIN_URL
So in your settings add LOGIN_URL = '/login/'
If the user is logged in the views will work perfectly.
Addition to that, (template level)
You can also check authentication in html,
{% if user.is_authenticated %}
#html
{% else %}
show something
{% endif %}

Why am I getting a 403 error “CSRF token missing” with Django?

I’m using REST Easy in Firefox to make a POST request to a simple form in Django, but it’s giving me a 403 error “2295 CSRF token missing or incorrect”.
This is my views.py (since I’m using the net behind a proxy):
from django.shortcuts import render
import urllib2
def home(request):
if request.method == 'POST':
post = request.POST
if 'passkey' in post:
if post['passkey'] == '123':
proxy = urllib2.ProxyHandler({'http': 'http://070.13095070:pujakumari123#10.1.1.19:80'})
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)
urllib2.install_opener(opener)
j = urllib2.urlopen(post['url'])
j_obj = json.load(j)
return HttpResponse(j_obj)
else:
return render(request, 'packyourbag/home_page.html')
and my template file:
<html>
<body>
<form id="form" method="post">
{% csrf_token %}
url:<input type="text" name="url"/>
Pass Key:<input type="text" name="passkey"/>
<button type="submit" name="url_post">
Post
</button>
</form>
</body>
</html>
I’m passing a URL and passkey, and I don't know how to pass a CSRF token (I don’t even know if I have to pass this or not).
You can disable the CSRF token requirement by putting #csrf_exempt before your view:
First import the decorator at the top of your views.py:
from django.views.decorators.csrf import csrf_exempt
Then decorate your view like:
#csrf_exempt
def home(request):
Warning: This will make your view vulnerable to cross site request forgery attacks. See https://docs.djangoproject.com/en/dev/ref/csrf/ for details.
It is because you aren't passing the CSRF Token through with rest-easy. You can either do as #Selcuk suggested and wrap your view function with #csrf_exempt while testing, or you can find the CSRF Token and POST that with rest-easy

Cross Site Request Forgery Issue in Django

I am getting this error when trying to implement csrf in django.
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect. (and bla bla bla)
My Views.py shows following:
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
from django.contrib.auth.forms import UserCreationForm
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('/accounts/loggedin')
else:
return HttpResponseRedirect('/accounts/invalid')
def loggedin(request):
return render_to_response('loggedin.html',{'full_name':request.user.username})
def invalid_login(request):
return render_to_response('invalid_login.html')
def logout(request):
auth.logout(request)
return render_to_response('logout.html')
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args ={}
args.update(csrf(request))
args['form'] = UserCreationForm()
return render_to_response('register.html')
def register_success(request):
return render_to_response('register_success.html')
My register.html reflects following:
{% extends 'base.html' %}
{% block content %}
<h2>Register</h2>
<form action="/accounts/register/" method="post">{% csrf_token %}
{{ form }}
<input type="submit" value="Register"/>
</form>
{% endblock %}
In urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^articles/', include('article.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/login/$', 'django_test.views.login'),
url(r'^accounts/auth/$', 'django_test.views.auth_view'),
url(r'^accounts/logout/$', 'django_test.views.logout'),
url(r'^accounts/loggedin/$', 'django_test.views.loggedin'),
url(r'^accounts/invalid/$', 'django_test.views.invalid_login'),
url(r'^accounts/register/$', 'django_test.views.register_user'),
url(r'^accounts/register_success/$', 'django_test.views.register_success'),
)
Please advise. I got cookies enabled in browser.
In register.html you need to add csrf token within <form> </form> like this: {% csrf_token %}, hopefully it will resolve the problem.
This might not be the best practice but you can add:
#csrf_exempt
Just above the functions in the view.py file.
See example in django-rest-framework tutorial:
Writing regular Django views

CSRF Token missing or incorrect

Beginner at Django here, I've been trying to fix this for a long time now.
I do have 'django.middleware.csrf.CsrfViewMiddleware' in my middleware classes and I do have the token in my post form.
Heres my code, what am I doing wrong?
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from chartsey.authentication.forms import RegistrationForm
from django.template import RequestContext
from django.core.context_processors import csrf
def register(request):
if request.method == 'POST':
c = RequestContext(request.POST, {})
form = RegistrationForm(c)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/")
else:
form = RegistrationForm()
return render_to_response("register.html", {'form': form, }, )
Here's my Template:
{% block content %}
<h1>Register</h1>
<form action="" method="POST"> {% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
{% endblock %}
Update: This answer is from 2011. CSRF is easy today.
These days you should be using the render shortcut function return render(request, 'template.html') which uses RequestContext automatically so the advice below is outdated by 8 years.
Use render https://docs.djangoproject.com/en/2.2/topics/http/shortcuts/
Add CSRF middleware https://docs.djangoproject.com/en/2.2/ref/csrf/
Use the {% csrf_token %} template tag
Confirm you see the CSRF token value being generated, AND submitted in your form request
Original Response
My guess is that you have the tag in the template but it's not rendering anything (or did you mean you confirmed in the actual HTML that a CSRF token is being generated?)
Either use RequestContext instead of a dictionary
render_to_response("foo.html", RequestContext(request, {}))
Or make sure you have django.core.context_processors.csrf in your CONTEXT_PROCESSORS setting.
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/
Or add the token to your context manually
Just add this to your views
return render_to_response("register.html", {'form': form, }, context_instance = RequestContext(request))
It will work!!
Try using render instead of render_to_response:
from django.shortcuts import render
render(request, "foo.html", {})
Django - what is the difference between render(), render_to_response() and direct_to_template()?
As stated in the link above it was introduced in Django 1.3 and automatically uses RequestContext
for Django version 3.0 add the below annotation
#csrf_protect
def yourfunc(request):
return render(request, '../your.html', None)
And don't forget add the below tag in your field
<form action="add/" method="post">
{% csrf_token %}
...
</form>
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.
The addition of RequestContext is the key when using render_to_response as mentioned by #Yuji 'Tomita' Tomita and #Njogu Mbau. However, what initially threw me off when I was struggling with this problem was that I had to add RequestContext to both the function in views.py that initially loads the template and to the function in views.py that handles the submission from the template.
Also, just for reference, here are some other links that discuss this same problem
Django - CSRF token missing or incorrect
Django 403 CSRF token missing or incorrect
Django --CSRF token missing or incorrect
Django CSRF Cookie Not Set *
Also got this error randomly on some pages after I installed django-livereload-server. Uninstalling django-livereload-server did the trick.
I had this issue too, but honestly, I hit refresh on my browser a few minutes later without changing anything and it worked that time. I had this message in my command line as so it might provide a clue as to what was causing the issue:
Not Found: /css/reset/reset.css
[03/Jul/2020 20:52:13] "GET /css/reset/reset.css HTTP/......
DJANGO/AJAX WORKFLOW FULL METHOD IS HERE :)
const url = "{% url 'YOUR_URL_NAME' pk=12345 %}".replace(/12345/, id.toString());
$.ajax({
type: 'POST',
url: url,
data: {'id':id, "csrfmiddlewaretoken": '{{csrf_token}}'},
beforeSend: function() { $('#response').text('Please wait ...'); },
success: function (response) {
console.log(response)
},
error: function (response) {
console.log(response)
}
})
Hope It Will Work !!!
What worked for me was commenting out the below line from my settings.py
'django.middleware.csrf.CsrfViewMiddleware'

csrf error in django

I want to realize a login for my site. I basically copied and pasted the following bits from the Django Book together. However I still get an error (CSRF verification failed. Request aborted.), when submitting my registration form. Can somebody tell my what raised this error and how to fix it?
Here is my code:
views.py:
# Create your views here.
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/books/")
else:
form = UserCreationForm()
return render_to_response("registration/register.html", {
'form': form,
})
register.html:
<html>
<body>
{% block title %}Create an account{% endblock %}
{% block content %}
<h1>Create an account</h1>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Create the account">
</form>
{% endblock %}
</body>
</html>
I was having the exact same issue - and Blue Peppers' answer got me on the right track. Adding a RequestContext to your form view fixes the problem.
from django.template import RequestContext
and:
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/books/")
else:
form = UserCreationForm()
c = {'form': form}
return render_to_response("registration/register.html", c, context_instance=RequestContext(request))
This fixed it for me.
I'm using Django 1.2.3, I had a few intermittent problems:
Things to do:
Ensure the csrf token is present in your template:
<form action="" method="post">{% csrf_token %}
Use a RequestContext:
return render_to_response('search-results.html', {'results' : results}, context_instance=RequestContext(request) )
Make sure you use a RequestContext for GETs as well, if they are handled by the same view function, and render the same template.
i.e:
if request.method == 'GET':
...
return render_to_response('search-results.html', {'results':results}, context_instance=RequestContext(request) )
elif request.method == 'POST':
...
return render_to_response('search-results.html', {'results':results}, context_instance=RequestContext(request))
not:
if request.method == 'GET':
...
return render_to_response('search-results.html', {'results':results})
elif request.method == 'POST':
...
return render_to_response('search-results.html', {'results':results}, context_instance=RequestContext(request))
Ensure 'django.middleware.csrf.CsrfViewMiddleware' is listed in your settings.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
Assuming you're on Django 1.2.x, just add this before {{form.as_p}}:
{% csrf_token %}
And to understand WHY, check out the CSRF docs
You need to add csrf(request) to your context.
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.core.context_processors import csrf
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/books/")
else:
form = UserCreationForm()
con = {'form': form}
con.update(csrf(request))
return render_to_response("registration/register.html", con)
You might need to turn your context into a Context object for this, not a dict, but the principle is sound.
Add these 2 middlewares to the settings file if you don't want to add {% csrf_token %} to each form.
MIDDLEWARE_CLASSES = (
#...
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
)
Later answer.
Now render can use instead of context_instance=RequestContext(request)
from django.shortcuts import render
return render(request, "registration/register.html", {
'form': form,
})
Try removing the following line from your settings.py's MIDDLEWARE list if you intend to use the {% csrf_token %}:
'django.middleware.csrf.CsrfViewMiddleware',
Worked for me......

Categories