How does Django 1.4 CSRF work? - python

I have that urls.py:
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(
r'^login/$',
'django.contrib.auth.views.login',
{'template_name': 'loyalty/login.html'},
name='login'
),
url(
r'^logout/$',
'django.contrib.auth.views.logout',
{'next_page': '/', },
name='logout'),
)
and have template login.html*:
{% extends "loyalty/auth.html" %}
{% load i18n %}
{% block auth_form %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<form action="" method="post" id="login-form">{% csrf_token %}
{% if form.username.errors %}{{ form.username.errors }}{% endif %}
{{ form.username }}
{% if form.password.errors %}{{ form.password.errors }}{% endif %}
{{ form.password }}
<input type="hidden" name="this_is_the_login_form" value="1" />
<input type="hidden" name="next" value="{{ next }}" />
<button type="submit" name="submit">{% trans 'Log in' %}</button>
</form>
{% endblock %}
and i have in settings.py:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
But this gives me this error:
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF cookie not set.
In administrative interface, I have same problem.
What can I do to solve this problem?

You probably aren't passing the Request context from your view.
Example:
def show_form(request):
form = MyForm()
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
return render_to_response("template_to_display.html", {'form':form}, context_instance = template.RequestContext(request))
Update: I would suggest rearranging your middleware. Try removing the localemiddleware or placing it at last. The django default is this

I solved this problem. Problem in browser. Tried an other browser and all works fine. Didn't understand why I had this problem, because I tried clean cache and cookies.

Related

How to add translation fields to templates using django-modeltranslation?

I am trying to translate my webpage using django-modeltranslation. I have complete the setup with the help of documentation provided but I am facing problem to display the model translated fields to templates. Can you help?
Here is what I have done.
# settings.py
def gettext(s):
return s
LANGUAGES = (
('en', gettext('English')),
('de', gettext('German')),
)
MODELTRANSLATION_TRANSLATION_FILES = (
'main.translation',
)
in app translation.py file
# project/app/translation.py
from modeltranslation.translator import translator, TranslationOptions
from .models import Post
class PostTranslationOptions(TranslationOptions):
fields = ('title', 'description')
translator.register(Post, PostTranslationOptions)
project urls.py file.
# urls.py
from django.contrib import admin
from django.urls import path, include
import debug_toolbar
from django.conf.urls.i18n import i18n_patterns
urlpatterns = [
path('admin/', admin.site.urls)
]
urlpatterns += [
path(r'^__debug__/', include(debug_toolbar.urls)),
]
urlpatterns += i18n_patterns(path('', include('main.urls')))
Views.py
# views.py
def ceo_dashboard(request):
post = Post.objects.all().select_related()
return render(request, 'main/dashboard_page.html', {'user': request.user, 'Posts': post})
template file
<h2 style="color:#0B2161;" >{{ post.title }}</h2>
<hr>
<p>{{ post.description }}</p>
<h5>Uploaded by : {{post.user}}</h5>
<hr>
Now I have no idea how to display these fields to templates.
You also need to add a Middleware called LocaleMiddleware, which activates translation for your project:
MIDDLEWARE = [
# ....
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware', # THIS ONE
'django.middleware.common.CommonMiddleware',
]
Read more about it in the Django documentation here: How Django discovers language preference
After that, you also need to add the language re-directer in your main template:
{% load i18n %}
<form action="{% url 'set_language' %}" method="post">{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}">
<select name="language">
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}>
{{ language.name_local }} ({{ language.code }})
</option>
{% endfor %}
</select>
<input type="submit" value="Go">
</form>
Now you can go to your admin and add Post where the django admin asks to enter different translation into the appropriate forms for the specified fields (in your case, 'title', 'description')
Hope this help you to solve the problem!

Django HoneyPot Change Password Issue

I would appreciate if you could give me any clue! As I don't have experience in this, probably I've misunderstood smth.
I'm using honeypot, more specifically honeypot.middleware.HoneypotMiddleware with HONEYPOT_FIELD_NAME in my API (settings.py).
As for the moment it's enough, I'm using the basic implementation for login, password change, reset from django.contrib.auth. In login I did a small customization so I added it in the url (authentication_form=CustomAuthenticationForm).
So I don't konw what I'm missing because the login page works (it is also a form), but the password change, reset ones are returning 400 Bad Request. Honey Pot Error (honey_pot_fieldname). Request aborted.
django: 2.1.2
django-honeypot: 0.7.0
[Updating with code]
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
....
'honeypot',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'honeypot.middleware.HoneypotMiddleware',
]
HONEYPOT_FIELD_NAME = config('HONEYPOT_FIELD_NAME')
forms.py
from django.contrib.auth.forms import AuthenticationForm
class CustomAuthenticationForm(AuthenticationForm):
error_messages = {
'invalid_login': _(
"Please enter a correct %(username)s and password. Note that both "
"fields may be case-sensitive."
),
'inactive': _("This account is inactive."),
'suspended': _("Your account has been temporarily suspended. For more information,\
please contact us."),
}
def clean(self)
def confirm_login_allowed(self, user)
urls.py
from django.contrib.auth import views as auth_view
urlpatterns = [
....
# ---- BASIC USER AUTHENTICATION (DJANGO)
path('api/login/', auth_view.LoginView.as_view(authentication_form=CustomAuthenticationForm), name='login'),
path('api/logout/', auth_view.LogoutView.as_view(), name='logout'),
# ---- PASSWORD CHANGE, RESET
path('api/password_change/', auth_view.PasswordChangeView.as_view(), name='password_change'),
path('api/password_change_done/', auth_view.PasswordChangeDoneView.as_view(),
name='password_change_done'),
....
]
[Templates]
templates/resgistration/login.html
{% extends 'base.html' %}
{% load i18n widget_tweaks %}
{% block head %}
{% load bootstrap3 %}
{{ form.media }}
{% endblock %}
{% block content %}
<div class="col-sm-4 col-sm-offset-4" style="margin-top:20px;">
<h1 class="display-4 text-center" >User login</h1>
<legend></legend>
<form method="post">
{% csrf_token %}
{% bootstrap_form form layout='inline' %}
{% buttons %}
<button type="submit" class="btn btn-primary center-block" style="margin-top: 20px">Log in</button>
{% endbuttons %}
</form>
</div>
{% endblock %}
templates/resgistration/password_change_form.html
{% extends 'base.html' %}
{% load i18n widget_tweaks %}
{% block head %}
{% load bootstrap3 %}
{{ form.media }}
{% endblock %}
{% block content %}
<div class="col-sm-4 col-sm-offset-4" style="margin-top:20px;">
<h1 class="display-4 text-center" >{{ title }}</h1>
<legend></legend>
<form method="post">
{% csrf_token %}
{% bootstrap_form form layout='inline' %}
{% buttons %}
<button type="submit" class="btn btn-primary center-block" style="margin-top: 20px">Change password</button>
{% endbuttons %}
</form>
</div>
{% endblock %}
Thanks in advance!
[Updating with solution]
Finally I achieved it!
I only had to add at the top of the template change_password_form.html the line
{% load honeypot %}
and within the form including the tag:
{% render_honeypot_field "field_name" %}
For achieve this helped me this article
django-honeypot
Hope that will be helpful for others.

When we extend an allauth view and create a new url based on that view is the old "/accounts/*" URLs of django allauth still required?

I extended the SignupView of django-allauth and created a url "/account-signup/" and also some minor changes in the template and I'm using the url name of my url. So, it keeps showing error that:
NoReverseMatch at /account-signup/
Reverse for 'account_login' not found. 'account_login' is not a valid view function or pattern name.
I've tried searching where the url name account_login is used in the template. Also, I've tried enabling the default URLs given by django allauth. It doesnt show error when the allauth URLs are included in the urls.py file.
/signup.html
{% extends "account/base.html" %}
{% load i18n %}
{% block head_title %}{% trans "Signup" %}{% endblock %}
{% block content %}
<h1>{% trans "Sign Up" %}</h1>
<p>{% blocktrans %}Already have an account? Then please sign in.{% endblocktrans %}</p>
<p>some content from sugat</p>
<form class="signup" id="signup_form" method="post" action="{% url 'my_app:custom_signup' %}">
{% csrf_token %}
{{ form.as_p }}
{% if redirect_field_value %}
<input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
{% endif %}
<button type="submit">{% trans "Sign Up" %} »</button>
</form>
{% endblock %}
/my_app/urls.py
from django.conf.urls import url
from .views import *
app_name = "my_app"
urlpatterns = [
url(r'^account-signup/$', AccountSignUp.as_view(), name="account_signup"),
]
/myproject/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url(r'^accounts/', include('allauth.urls')),
url(r'', include("my_app.urls")),
]

Problem with ERR_TOO_MANY_REDIRECTS django 2.1

I started to create login module in django. Login module is ok but I have problem with logout. When i click Logout - we see "error -ERR_TOO_MANY_REDIRECTS"
Probably something in this file is incorect: account/urls.py
from django.conf.urls import url
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'account'
urlpatterns = [
path('', auth_views.LoginView.as_view(template_name='account/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='registration/logout.html'), name='logout'),
path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'),
path('dashboard/', views.dashboard, name='dashboard'),
base.html
<body>
<div id="header">
{% if request.user.is_authenticated %}
<ul class="menu">
<li {% if section == "dashboard" %} class="selected"{% endif %}>
Panel główny
</li>
<li {% if section == "images" %} class="selected"{% endif %}>
Obrazy
</li>
<li {% if section == "people" %} class="selected"{% endif %}>
Ludzie
</li>
</ul>
{% endif %}
<span class="user">
{% if request.user.is_authenticated %}
Witaj, {{ request.user.first_name }}
Wyloguj
{% else %}
Zaloguj
{% endif %}
</span>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
logout.html
{% extends "base.html" %}
{% block title %} Wylogowanie {% endblock %}
{% block content %}
<h1>Wylogowanie</h1>
<p>Zostales wylogowany. Mozesz
zalogowac sie ponownie</p>
{% endblock %}
settings.html
...
LOGIN_REDIRECT_URL = reverse_lazy('account:dashboard')
LOGIN_URL = reverse_lazy('account:login')
LOGOUT_REDIRECT_URL = reverse_lazy('account:logout')
show error
You've set LOGOUT_REDIRECT_URL to point back to the LogoutView which will cause a redirect loop. The LOGOUT_REDIRECT_URL should point to a URL that the user will be redirected to after they've logged out using the LogoutView.
Setting LOGOUT_REDIRECT_URL will override any template that's been set. Since you've explicitly set a template for the LogoutView in your urls.py, you should remove LOGOUT_REDIRECT_URL from your settings which will allow the template to be rendered.

Production only: sometimes get 403 CSRF verification failed

I have a login form that logs the users into the admin site. It works fine in development, and mostly works fine in production, but sometimes it gives a 403 CSRF verification failed error. Note that this happens to users that were able to log in before, so I can't imagine it's an issue with their browser.
It looks like jenniwren had a similar issue in this comment. They never asked a question about it, and the other commenters had no clue why that would happen.
Here's what I have:
urls.py
urlpatterns += patterns('django.contrib.auth.views',
url(r'^logout$', 'logout', {'next_page': 'mysite_login'}, name='mysite_logout'),
url(r'^login$', 'login', name='mysite_login'),
url('^', include('django.contrib.auth.urls')),
)
main/registration/login.html
{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
{% if form.errors and not form.non_field_errors %}
<p class="errornote">Please correct the error(s) below.</p>
{% endif %}
{% if form.non_field_errors %}
{% for error in form.non_field_errors %}
<p class="errornote">
{{ error }}
</p>
{% endfor %}
{% endif %}
<form action="{{ app_path }}" method="post" id="login-form">
{% csrf_token %}
<div class="form-row">
{% if form.errors %}
{ form.username.errors }}
{% endif %}
{{ form.username.label_tag }}
{{ form.username }}
</div>
<div class="form-row">
{% if form.errors %}
{{ form.password.errors }}
{% endif %}
{{ form.password.label_tag }}
{{ form.password }}
</div>
<input type="hidden" name="next" value="{{ next }}" />
<div class="submit-row">
<input type="submit" value="Log in" />
</div>
<div class="password-reset-link">
Forgot your password?
</div>
</form>
{% endblock content %}
settings.py
INSTALLED_APPS = (
'filebrowser',
'grappelli',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'psycopg2',
'main',
'mysite'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware'
)
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
CSRF_COOKIE_HTTPONLY = True
This problem might occur if:
A user opens the login page in two different tabs
A user logins in one tab.
A user tries to login again in a different tab (although he is already logged in).
If your CSRF_FAILURE_VIEW shows your site template, you might be able to let the users know they are already logged in, and do not need to refresh the page.
This is a message I got whed Debug=True:
The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.
I think this answer will help you, you can also use #csrf_exempt annotation
over your function(view) like this:
#csrf_exempt
def foo():
return 'bar'
django doc on this subject: https://docs.djangoproject.com/en/3.0/ref/csrf/
I was doing some proxying for the admin url and fixed my issue by editing my settings.py file and adding:
CSRF_TRUSTED_ORIGINS = [".subdomain.com"]
Using my organisation's gsuite subdomain. See the django docs for reference

Categories