CSRF verification failed. Request aborted. Python 1.8 - python

Good Afternoon,
I am new to django, I am creating a Login Portal, but i get the following error | CSRF verification failed. Request aborted.
I am using Django 1.8 and Python 3.4 please help me, If you need anything else please let me know
here is my views.py:
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
def nuevo_usuario(request):
if request.method == 'POST':
formulario = UserCreationForm(request.POST)
if formulario.is_valid():
formulario.save()
return HttpResponseRedirect('/')
else:
formulario = UserCreationForm()
return render_to_response('registration/nuevo_usuario.html', {'formulario':formulario}, context_instance = RequestContext(request))
def ingresar(request):
if request.method == 'POST':
formulario = AuthenticationForm(request.POST)
if formulario.is_valid():
usuario = request.POST['username']
clave = request.POST['password']
acceso = authenticate(username=usuario, password=clave)
if acceso is not None:
if acceso.is_active:
login(request, acceso)
return HttpResponseRedirect('/privado')
else:
return render_to_response('registration/noactivo.html', context_instance = RequestContext(request))
else:
return render_to_response('registration/nousuario.html', context_instance = RequestContext(request))
else:
formulario = AuthenticationForm()
return render_to_response('registration/ingresar.html', {'formulario':formulario}, context_instance = RequestContext(request))
Este es mi archivo ingresar.html
{% extends 'base.html' %}
{% block titulo %}Ingresa al sistema{% endblock %}
{% block encabezado %}
Ingresa
{% endblock %}
{% block content %}
<div class="main">
<div class="login-form">
<h1> C. Monitoring Center</h1>
<div class="head">
</div>
<form id = 'formulario' method = 'post' action = ''> {% csrf_token %}
<input type="text" class="text" placeholder="Username" required autofocus>
<input type="password" placeholder="Password" required>
<div class="submit">
<input type="submit" onclick="#" value="LOGIN" >
</div>
<p>Forgot Password ?</p>
</form>
</div>
{% endblock %}
Este es mi archivo url.py
"""centinell URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from login.views import *
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$','login.views.ingresar'),
url(r'^usuario/nuevo$', 'login.views.nuevo_usuario'),
url(r'^ingresar/$', 'login.views.ingresar'),
]

you need a csrf token that django provides ... (necesitas la clave csrf q django tiene incluido)
<form id = 'formulario' method = 'post' action = ''> {% csrf_token %}
<input type="text" class="text" placeholder="Username" required autofocus>
<input type="password" placeholder="Password" required>
<div class="submit">
<input type="submit" onclick="#" value="LOGIN" >
</div>
{% csrf_token %} <!-- THIS!!!!! Aqui !!!-->
<p>Forgot Password ?</p>
</form>
or if you want you can just disable csrf protections (o si quierres se puede apagar los protejos de csrf)
#csrf_exempt # you need to import from django.contrib.auth
def ingresar(request):

Related

Fill out the form and save it in db base

I am working on a Django project and I want to fill out a form and save the data in the db database and then be able to show it on another page, I managed to create the form, following some tutorials, but it does not write me anything in the database. Here's how I currently have things:
forms.py
from django import forms
from .models import AusenciasForm
from django.contrib.auth.models import User
class AusenciasForm(forms.ModelForm):
class Meta:
model = AusenciasFormulario
fields = '__all__'
widgets = {'fecha': forms.DateInput(attrs={'type': 'date'})}
models.py
from django.db import models
from django.utils import timezone
import datetime
from django.contrib.auth.models import User
from django.urls import reverse
class AusenciasFormulario(models.Model):
#razon = models.ModelChoiceField(label="Razón", queryset=razones.object.all())
fecha = models.DateField(("Date"),default=datetime.date.today)#label="Fecha", required=True
razon = [
('Estudios/Examen','Estudios/Examen'),
('Enfermedad','Enfermedad'),
('Lesión','Lesión'),
('Motivos personales','Motivos personales'),
('Motivos familiares','Motivos familiares'),
('Otros','Otros')
]
motivo = models.CharField(max_length=100, choices=razon, default='Otros')
comentarios= models.CharField(max_length=200,blank=True)
jugador = User
views.py
class FormularioAusenciaView(HttpRequest):
def index(request):
ausencias_formulario = AuForm.objects.all()
return render(request, 'blog/ausencias.html', {'ausencias_formulario':ausencias_formulario})
def procesar_formulario(request):
#if request.method == 'POST':
form = AusenciasForm(request.POST)
if form.is_valid():
form.save()
form = AusenciasForm()
return HttpResponseRedirect('ausencias/') #Add your route name, where you want to go after form save
else:
form = AusenciasForm()
return render(request, 'blog/formularioAusencia.html', {'form':form})
Urls.py
from django.urls import path
from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView,UserPostListView, FormularioAusenciaView, ausencias
from .import views
from django.contrib.auth.decorators import login_required
urlpatterns = [
path('', login_required(PostListView.as_view()), name='blog-home'),
path('user/<str:username>',login_required( UserPostListView.as_view()), name='user-posts'),
path('post/<int:pk>/',login_required( PostDetailView.as_view()), name='post-detail'),
path('post/new/',login_required( PostCreateView.as_view()), name='post-create'),
path('post/<int:pk>/update/',login_required( PostUpdateView.as_view()), name='post-update'),
path('post/<int:pk>/delete/',login_required( PostDeleteView.as_view()), name='post-delete'),
path('about/', views.about, name='blog-about'),
path('formularioAusencia/',login_required( FormularioAusenciaView.index), name='formularioAusencia'),
#path('asistencia_done/',formularioAusencia, name='asistencia_done'),
path('ausencias/',login_required( views.ausencias), name='ausencias'),
]
the template
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{ user.email }}</p>
</div>
</div>
{% if user.is_authenticated %}
<p></p><a class="mr-2">Rellenar si no vas a poder acudir a un próximo entrenamiento o partido</a></p>
<!--<label><input type="checkbox" id="cbox1" value="first_checkbox"></label><br>-->
<form method="POST" action="{% url 'ausencias' %}">{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-danger btn-sm mt-1 mb-1" type="submit">Enviar</button>
</form>
</div>
<div class="form-group">
</div>
{% endif %}
</div>
{% endblock content %}
In forms.py:
You have imported wrong model name:
change this
from .models import AusenciasForm
To this:
from .models import AusenciasFormulario
And in views.py file:
You have not added any orm query so that's why it is not saving in db.
views.py :
Do this:
def index(request):
ausencias_formulario = AusenciasFormulario.objects.all() #Here i have retrieved data using orm
return render(request, 'blog/formularioAusencia.html', {'ausencias_formulario':ausencias_formulario})
def procesar_formulario(request):
if request.method == 'POST':
form = AusenciasForm()
if form.is_valid():
form.save()
return HttpResponseRedirect('/home/') #Add your route name, where you want to go after form save
else:
form = AusenciasForm()
return render(request, 'blog/formularioAusencia.html', {'form':form})
And in your templates:
formularioAusencia.html
<form method='post'>
{{form}}
<input type="submit" /> #Added new code here
</form>
After submitting above form, using below code, you will get that fields.
Add below code after the form tag.
To display all the fields to templates add the below code in template:
{% for field in ausencias_formulario %}
{{field.fecha}}
#Add remaining fields here to display
{% endfor %}

django: "'str' object has no attribute 'regex'

I'm building a little web server using django but I keep getting 'str' object has no attribute 'regex' in my template where it says {% url 'signup' %} and {% url 'login' %}. I guess this will be something to do with URL binding, or probably me not having imported the right module that is needed to refer to a URL by its name attribute. But I can't figure a way around this. Thanks in advance.
Template
{% include "header.html" %}
<div class="container">
<div class="page-header"><h3>로그인</h3></div>
<form method="post" action="{% url 'login' %}" role="login">
{% csrf_token %}
<div class="form-group">
<label>아이디</label>
<input type="text" name="username" placeholder="아이디를 입력하세요" class="form-control" />
</div>
<div class="form-group">
<label>비밀번호</label>
<input type="password" name="password" placeholder=" 암호를 입력하세요" class="form-control" />
<input type="hidden" name="next" value="/" />
</div>
<div class="form-group">
<div class="btn-group pull-right">
<input type="submit" value="로그인" class="btn btn-primary"/>
가입하기
</div>
</div>
</form>
</div>
{% include "footer.html" %}
Views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from docx import Document
from exam.models import *
def login(request):
return render(request, 'login.html')
def signup(request):
try:
if request.session["error"]:
error_message = request.session["error"]
del request.session["error"]
except KeyError:
error_message = None
context = {
"error_message" : error_message
}
return render(request, "signup.html", context)
def signup_submit(request):
try:
username = request.POST["username"].strip()
password = request.POST["password"].strip()
password_confirm = request.POST["password_confirm"].strip()
full_name = request.POST["full_name"].strip()
student_num = request.POST["student_num"].strip()
if username and password and password_confirm and full_name and student_num:
user = User(username=username, full_name=full_name, student_num=student_num)
user.set_password(password)
user.save()
return redirect("index")
except KeyError:
request.session["error"] = "올바른 요청이 아닙니다."
return redirect("signup")
else:
request.session["error"] = "입력한 정보가 올바르지 않습니다."
return redirect("signup")
URLS.py
from django.conf.urls import include, url, patterns
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}, name='login'),
url(r'^signup/$', 'exam.views.signup', name='signup'),
url(r'^signup/submit/$', 'exam.views.signup_submit', name='signup_submit'),
Error Traceback:
AttributeError at /
'str' object has no attribute 'regex'
Request Method: GET
Request URL: http://192.168.56.101:8000/
Django Version: 1.7.6
Exception Type: AttributeError
Exception Value:
'str' object has no attribute 'regex'
Exception Location: /home/web/venv/lib/python3.4/site-packages/django/core/urlresolvers.py in _populate, line 282
Python Executable: /home/web/venv/bin/python

What should return when using CSRF tokens with class-based views?

Forbidden (403) CSRF verification failed.
Request aborted. Reason given for failure: CSRF cookie not set.
I get the above error and there are a few solutions out there, but not for class-based views. What should def get_context_data(self, **kwargs): be returning? Below the message, it suggests 4 solutions, and the following suggestion catches my attention. So perhaps I should be returning a RequestContext somehow?
The view function uses RequestContext for the template, instead of Context.
I'm already using {% csrf_token %}, cookies are enabled and I have it included in the middleware. So I think I may be returning the wrong thing but all the other examples around here use function views.
My template snippet:
{% if not user.is_authenticated %}
<form id="login" method="post" action="login">{% csrf_token %}
<input type="text" name="username" value="" placeholder="Email">
<input type="password" name="password" value="" placeholder="Password">
<input type="submit" name="commit" value="Login">
</form>
{% elif user.is_authenticated %}
<p>Welcome, {{ user.get_displayname }}.</p>
{% endif %}
My urls.py:
from django.conf.urls import patterns, include, url
from mainapp.views import Index, LoginResponse
from django.contrib import admin
admin.autodiscover()
from mainapp import views
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', Index.as_view()),
url(r'^login$', LoginResponse.as_view()),
)
My LoginResponse class view:
class LoginResponse(TemplateView):
template_name = 'index.html'
def get_context_data(self, **kwargs):
context = super(LoginResponse, self).get_context_data(**kwargs)
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
return context
For CSRF verification there is no difference between function based and class based views. This verification is done at middleware level.
So show your template and urls.py please.

Django Model form don't update database records

I am new in django and I want to create a form to update some database entries.
this is a simple form where I have a simple input text where I write the id of the record that I want to update:
main.html
<form method='post' action='/config/{{ idprov }}' >
<input type="text" class="form-control" name="idprov" id="idprov" value ="{{ idprov }}" />
<input class="btn btn-danger" type="submit" value="Config">
</form>
forms.py
from django import forms
from .models import Proveedor, Estado, Config
class ConfigForm(forms.ModelForm):
class Meta:
model = Config
this is my views.py:
def configView(request,idprov):
prov = Config.objects.get(idproveedor=idprov)
if request.method == 'POST':
form = ConfigForm(request.POST or None, instance=prov)
if form.is_valid():
form.save(commit=false)
return HttpResponseRedirect('/monitor/')
else:
form = ConfigForm( instance=prov)
return render_to_response('config.html',
{'form':form})
my template config.html:
{% extends 'base.html' %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-md-4">
<form method='POST' action='' >
<div class="form-group">{% csrf_token %}
{{ form.as_p }}
</div>
<button type='submit' class="btn btn-primary">Grabar</button>
</form>
</div>
</div>
</div>
{% endblock %}
my urls.py:
from django.conf.urls import patterns, include, url
from prov.views import home
from prov.views import proveedores
from prov.views import estado
from prov.views import monitorViewV2
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'prov.views.home', name='home'),
url(r'^proveedores/$', 'prov.views.proveedores', name='proveedor'),
url(r'^estado/$', 'prov.views.estado', name='estado'),
url(r'^monitor/$', 'prov.views.monitorView', name='monitor'),
url(r'^monitorv/$', 'prov.views.monitorViewV2', name='monitorv2'),
url(r'^config/(?P<idprov>\d+)/$', 'prov.views.configView',name='config'),
url(r'^admin/', include(admin.site.urls)),
)
But I receive the error Page not found.
I try to follow other snippets and always raise different errors.
I think the error is in the urls.py and in the way I pass the argument from the main.html.
Any advice or snippet will be very appreciated
Thanks in advance
First you have a form.save(commit=false) in your view without saving it later, thats mean the data is never saved into the model.
Second in your template config.html the form action is empty <form method='POST' action=''> change for <form method='POST' action='.'>
I hope that help to you.

How to configure HTML form to work with django models?

I am trying to configure HTML formto work with Django Models rather than using built-in Forms in the framework. I have made the form using Html below and have pasted the code for Model, View and Urls.py. The problem is when I click the submit button, it doesn't perform any action. I am able to view the form but it doesn't serves the purpose. I know the question is very lame, but how would configure the HTML to work with the django model so that the data can be saved to the database?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body style="font-family:Courier New">
<h1>Add / Edit Book</h1>
<hr/>
<form id="formHook" action="/istreetapp/addbook" method="post">
<p style="font-family:Courier New">Name <input type="text" placeholder="Name of the book"></input></p>
<p style="font-family:Courier New">Author <input type="text" placeholder="Author of the book"></input></p>
<p style="font-family:Courier New"> Status
<select>
<option value="Read">Read</option>
<option value="Unread">Unread</option>
</select>
</p>
<input type="submit" id="booksubmit" value="Submit"></input>
</form>
</body>
</html>
View
from django.shortcuts import HttpResponse
from istreetapp.models import bookInfo
from django.template import Context, loader
from django.shortcuts import render_to_response
def index(request):
booklist = bookInfo.objects.all().order_by('Author')[:10]
temp = loader.get_template('app/index.html')
contxt = Context({
'booklist' : booklist,
})
return HttpResponse(temp.render(contxt))
Model
from django.db import models
class bookInfo(models.Model):
Name = models.CharField(max_length=100)
Author = models.CharField(max_length=100)
Status = models.IntegerField(default=0) # status is 1 if book has been read
def addbook(request, Name, Author):
book = bookInfo(Name = Name, Author=Author)
book.save
return render(request, 'templates/index.html', {'Name': Name, 'Author': Author})
Urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('app.views',
url(r'^$', 'index'),
url(r'^addbook/$', 'addbook'),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
You forgot to define name in each of your input
<form id="formHook" action="/addbook/" method="post">
{% csrf_token %}
<p style="font-family:Courier New">
Name <input type="text" name="name" placeholder="Name of the book"></input>
</p>
<p style="font-family:Courier New">
Author <input type="text" name="author" placeholder="Author of the book"></input>
</p>
<p style="font-family:Courier New">
Status
<select name="status">
<option value="Read">Read</option>
<option value="Unread">Unread</option>
</select>
</p>
<input type="submit" id="booksubmit" value="Submit"></input>
</form>
Your addbook must be in the views.py not in your models.py.
You don't have to define templates/index.html in your render, it is understood in your settings
def addbook(request):
if request.method == 'POST':
name = request.POST['name']
author = request.POST['author']
bookInfo.objects.create(Name = name, Author=author)
return render(request, 'index.html', {'Name': name, 'Author': author})
main urlconf
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'project_name.views.index'),
url(r'^addbook/$', 'project_name.views.addbook'),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
You need to add name attributes to your html form then process the form submission in the view. Something like -
from django.http import HttpResponseRedirect
from django.shortcuts import render
def book_view(request):
if request.method == 'POST':
name = request.POST['name']
author = request.POST['author']
book = BookInfo(name=name, author=author)
if book.is_valid():
book.save()
return HttpResponseRedirect('your_redirect_url')
else:
return render(request, 'your_form_page.html')
Have a look at the docs on the request.POST dictionary.
However you really would be better off doing this with a django ModelForm -
class BookForm(ModelForm):
class Meta:
model = BookInfo # I know you've called it bookInfo, but it should be BookInfo
then in your view -
from django.http import HttpResponseRedirect
from django.shortcuts import render
def book_view(request, pk=None):
if pk:
book = get_object_or_404(BookInfo, pk=pk)
else:
book = BookInfo()
if request.method == 'POST':
form = BookForm(request.POST, instance=book)
if form.is_valid():
book = form.save()
return HttpResponseRedirect('thanks_page')
else:
form = BookForm(instance=book)
return render(request, 'your_form_page.html', {'form': form)
And your_form_page.html can be as simple as -
<form action="{% url book_view %}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Have a look at the docs on working with forms.

Categories

Resources