django csrf_token missing error - python

When I am trying to register, I'm getting an error:
Forbidden (403)
CSRF verification failed. Request aborted.
My Code:
#csrf_protect
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST, request.FILES)
if form.is_valid():
first_name = form.cleaned_data.get("firstname")
last_name = form.cleaned_data.get("lastname")
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = User.objects.create_user(username=username,password=password)
user.first_name = first_name
user.last_name = last_name
user.set_password(password)
user.is_active = True
user.save()
return HttpResponseRedirect('/home/')
else:
form = RegistrationForm()
return render_to_response('registration/registerHome.html',dict(form=form,
context_instance=RequestContext(request) ) )
my form.py
class RegistrationForm(forms.Form):
"""
A registration form to create normal user.
"""
firstname = forms.RegexField(regex=r'^\[a-zA-Z]+$',
widget=forms.TextInput(attrs={ 'required':True,
'max_length':30,
'autocomplete':'off',
'class':'form-control input-sm',
'placeholder':'First Name' }),
error_messages={ 'invalid': _("Only alphabets are allowed.") }
)
lastname = forms.RegexField(regex=r'^\[a-zA-Z]+$',
widget=forms.TextInput(attrs={ 'required':True,
'max_length':30,
'autocomplete':'off',
'class':'form-control input-sm',
'placeholder':'Last Name' }),
error_messages={ 'invalid': _("Only alphabets are allowed.") }
)
username = forms.RegexField(regex=r'^\w+$',
widget=forms.TextInput(attrs={'required':True,
'max_length':30,
'autocomplete':'off',
'class':'form-control input-sm',
'placeholder':'username'}),
error_messages={ 'invalid': _("Only [a-z A-Z 0-9 _] are allowed.") }
)
password = forms.CharField(widget=forms.PasswordInput(attrs={
'required':True,
'max_length':30,
'autocomplete':'off',
'class':'form-control input-sm',
'placeholder':'password',
'render_value':False })
)
def clean_username(self):
try:
user = User.objects.get(username__iexact=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError(_("Username already exists."))
class Meta:
model = User
my template.html
<form action="." method="post" role="form" id="register-form">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="submit" />
</form>
Someone, please help me, why I'm getting an error. I am trying to solve this problem for 1 week and still getting the error. Please help me.

You should use render and add else
Then do like
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST, request.FILES)
if form.is_valid():
first_name = form.cleaned_data.get("firstname")
last_name = form.cleaned_data.get("lastname")
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = User.objects.create_user(username=username,password=password)
user.first_name = first_name
user.last_name = last_name
user.set_password(password)
user.is_active = True
user.save()
return HttpResponseRedirect('/home/')
else:
return render(request, 'registration/registerHome.html',dict(form=form)))
else:
form = RegistrationForm()
return render(request, 'registration/registerHome.html',dict(form=form)))

You don't need to use the #csrf_protect decorator as long as the csrf middleware is added.The Middleware gives you blanket protection on all views - adding the decorator is redundant. The Django docs recommend using the Middleware over the decorator as it provides better protection.
Try after removing the decorator.

Try something like this. I remember sometime ago I had the same problem and declaring the c dictionary and passing it to the render_to_response solved my problem.
#csrf_protect
def register(request):
if request.method == 'POST':
# do your post stuff here
pass
else:
c = {}
c['form'] = RegistrationForm()
c['context_instance'] = RequestContext(request)
return render_to_response('registration/registerHome.html',c )

Try using https://docs.djangoproject.com/en/1.11/topics/http/shortcuts/#render
from django.shortcuts import render
#csrf_protect
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST, request.FILES)
if form.is_valid():
first_name = form.cleaned_data.get("firstname")
last_name = form.cleaned_data.get("lastname")
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = User.objects.create_user(username=username,password=password)
user.first_name = first_name
user.last_name = last_name
user.set_password(password)
user.is_active = True
user.save()
return HttpResponseRedirect('/home/')
else:
form = RegistrationForm()
return render(request, 'registration/registerHome.html',dict(form=form) ) )

Related

Form errors not displaying with Django Crispy Forms

I just started learning Django and Python some weeks back. Working on a project sign up page, everything works perfectly except that form errors are not displaying on the form itself but redirected to a debug error page with the below
ValidationError at /register/
['Username exists']
Request Method: POST
Request URL: http://127.0.0.1:8000/register/
Django Version: 3.2.5
Exception Type: ValidationError
Exception Value:
['Username exists']
During a new user profile registration, i am checking if the username used to register already exists or not and if it exists, i want to display an error to user that Username already exists.
Please see my code below:
forms.py
class RegistrationForm(forms.Form):
first_name = forms.CharField(label='First Name')
last_name = forms.CharField(label='Last Name')
username = forms.CharField(label='Username')
password = forms.CharField(
label='Password', widget=forms.PasswordInput(), min_length=8)
password_confirm = forms.CharField(
label='Confirm Password', widget=forms.PasswordInput())
email_address = forms.EmailField(label='Email')
phone_number = PhoneNumberField(label='Phone Number')
whatsapp_number = PhoneNumberField(label='WhatsApp Number', required=False)
COUNTRY_CHOICES = [
('', 'Choose...'),
]
country = forms.ChoiceField(label='Country', choices=COUNTRY_CHOICES)
referral_id = forms.CharField(label='Referral ID', required=False)
license_agreement = forms.BooleanField(
label='I agree to all the Terms and Conditions')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_id = 'create-account-form'
self.helper.form_action = 'register'
self.helper.form_show_errors = True
self.helper.layout = Layout(
Row(
Column('first_name'),
Column('last_name'), css_class='g-2'
),
Row(
Column(
PrependedText('username', '#')
),
Column('country'), css_class='g-2'
),
Row(
Column('password'),
Column('password_confirm'),
Column('referral_id'),
css_class='g-2'
),
Row(
Column('phone_number'),
Column('whatsapp_number'),
Column('email_address'), css_class='g-2'
),
Row('license_agreement'),
Row(Submit('submit', 'Create Account'))
)
def check_username(self):
data = self.cleaned_data['username']
if User.objects.filter(username__iexact=data).exists():
raise ValidationError('Username exists')
return data
def compare_passwords(self):
password1 = self.cleaned_data['password']
password2 = self.cleaned_data['password_confirm']
if password2 != password1:
raise ValidationError('Password does not match')
return password1
views.py
def reg_form(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
username = form.check_username()
password = form.compare_passwords()
email = form.cleaned_data['email_address']
user = User.objects.create_user(
username=username, email=email, password=password)
user.first_name = first_name
user.last_name = last_name
user.save()
user_info = UserInfo()
user_info.user = user
user_info.linked_user = user.username
user_info.phone_number = form.cleaned_data['phone_number']
user_info.whatsapp_number = form.cleaned_data['whatsapp_number']
user_info.country = form.cleaned_data['country']
user_info.referral_id = form.cleaned_data['referral_id']
user_info.save()
login(request, user)
return redirect(reverse('dashboard'), permanent=True)
else:
form = RegistrationForm()
return render(request, 'office/reg_form_hx.html', {'form': form})
template
{% extends './base.html' %}
{% block main %}
{% load crispy_forms_tags %}
{% crispy form %}
{% endblock main %}
I figured this out.
I was supposed to implement the form clean() method or the clean_fieldname() method for a specific field.
It should have been clean_username() and not check_username() in the forms.py file.
Thank you.

User creation - email field and image field not updating Postgres

In an extended user model with User and Profile created together. The user and related profile(Customer) is created but two fields 'email'(user email) field and 'photo'(image field) is not saved into database. Appreciate some fix:
views.py
def customer_register(request):
if request.method == 'POST':
user_form = UserRegistrationForm(request.POST)
profile_form = CustomerProfileForm(request.POST)
if user_form.is_valid() and profile_form.is_valid():
# Create a new user object but avoid saving it yet
new_user = user_form.save(commit=False)
# Set the chosen password
new_user.set_password(
user_form.cleaned_data['password'])
# Save the User object
new_user.save()
# Create the customer profile
customer = profile_form.save(commit=False)
customer.user = new_user
customer.save()
#Customer.objects.create(user=new_user,date_of_birth=customer.date_of_birth, photo=customer.photo, pincode=customer.pincode)
return render(request,
'registration/register_done.html',
{'new_user': new_user})
else:
messages.error(request, 'Error in creating your profile')
else:
user_form = UserRegistrationForm()
profile_form = CustomerProfileForm()
Forms.py
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(label='Password',
widget=forms.PasswordInput)
password2 = forms.CharField(label='Repeat password',
widget=forms.PasswordInput)
email = forms.EmailField(label='email', widget=forms.EmailInput, required=True)
class Meta:
model = User
fields = ['username', 'first_name', 'email']
def clean_password2(self):
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError('Passwords don\'t match.')
return cd['password2']
def clean_email(self):
email = self.cleaned_data.get('email')
if User.objects.filter(email=email).exists():
raise forms.ValidationError("Email exists. Please change email")
class CustomerProfileForm(forms.ModelForm):
pincode = INZipCodeField(label="PIN")
date_of_birth = forms.DateField(widget=forms.DateInput(format='%d/%m/%Y'), input_formats=('%d/%m/%Y',))
photo = forms.ImageField()
class Meta:
model = Customer
fields = ['pincode','date_of_birth','photo']
I figured out the email id issue was in the form, form had to return the email in the email validation function
clean_email(self):
email = self.cleaned_data.get('email')
if User.objects.filter(email=email).exists():
raise forms.ValidationError("Email exists. Please change email")
return email
In the views I had to add request for files(image) along with form:
profile_form = CustomerProfileForm(request.POST, request.FILES or None)
The image issue was in the registration html template. I updated the form to enctype "multipart/form-data" to take get image inputs
<form method="post" enctype="multipart/form-data" action="{% url 'customer_register' %}">
{% csrf_token %}

Django login error and cannot login

I try to find a similar question but I did not find the answer what I want. I am new to Django, I was trying to learn about authentication in Django but I got an error like this:
AttributeError: 'AnonymousUser' object has no attribute '_meta'
Here is my code:
views.py
def login(request):
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
username = request.GET['username']
password = request.GET['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request,user)
return redirect('/')
else:
error = " Sorry! Username and Password didn't match, Please try again ! "
return render(request, 'girl/login.html',{'error':error})
else:
form = LoginForm()
return render(request, 'girl/login.html', {"form":form})
forms.py
class LoginForm(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'password')
login.html
{% extends 'base.html' %}
{% block content %}
<h1>Login</h1>
{% if error %}
{{ error }}
{% endif %}
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="login">
</form>
{% endblock %}
Any help would be appreciated. Thanks!
You just need to inherit from forms.Form not forms.ModelForm,
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput())
Also, in your views, edit something like this,
def login(request):
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request,user)
return redirect('/')
else:
error = " Sorry! Username and Password didn't match, Please try again ! "
else:
form = LoginForm()
return render(request, 'girl/login.html', {"form":form})
You set password as a normal text. Try like this.
def login(request):
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
# normalized data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request,user)
return redirect('/')
else:
error = " Sorry! Username and Password didn't match, Please try again ! "
return render(request, 'girl/login.html',{'error':error})
else:
form = LoginForm()
return render(request, 'girl/login.html', {"form":form})

Attribute user.grade cannot be referenced in Django template

I have some code for a website that I'm building.
in my views.py, i have the following code:
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.conf.urls import url
from .models import UserInfo, Events
from django import forms
from .forms import RegisterForm, LoginForm, OrderForm
from django.contrib.auth.models import User
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login, logout
# Create your views here.
def home(request):
return render(request, 'student/index.html')
#csrf_exempt
def signin(request):
print "login"
if request.method == 'POST':
form = LoginForm(request.POST)
username = request.POST['username']
password = request.POST['password']
print "input username ", username
try:
if form.is_valid():
user = authenticate(username=username, password=password)
if user is not None:
print "user not none"
print user.username
print user.email
login(request,user)
return redirect("/")
else:
print "login failed"
raise forms.ValidationError({'username':['Invalid username/password']})
else:
print form.errors
except:
raise
else:
print "hello"
form = LoginForm()
return render(request, 'student/login.html', {'form': form})
#csrf_exempt
def signup(request):
print "signup"
if request.method == 'POST':
print "post signup"
form = RegisterForm(request.POST)
try:
if form.is_valid():
print form.cleaned_data
u = User.objects.create_user(form.cleaned_data['emailid'], form.cleaned_data['emailid'], form.cleaned_data['passwd1'] )
ui = UserInfo()
ui.user = u
ui.class_of = form.cleaned_data['gradyear']
ui.grade = form.cleaned_data['grade']
ui.balance = 0
ui.save()
user = authenticate(username=form.cleaned_data['emailid'], password=form.cleaned_data['passwd1'])
login(request,user)
print "after login in signup"
return redirect("/")
else:
print "error"
print form.errors
except:
raise
print "error here"
print form.errors
pass
#return render(request, 'student/register.html', {'form': form})
else:
form = RegisterForm()
return render(request, 'student/register.html', {'form': form})
def forgotpassword(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
print form.cleaned_data
return HttpResponseRedirect('/thanks/')
else:
print "INVALID"
print form.errors
else:
form = LoginForm()
return render(request, 'student/forgotpassword.html')
def studentinfo(request):
return render(request, 'student/studentinfo.html', {} )
def error(request):
return render(request, 'student/LoginError.html', {} )
def site_logout(request):
logout(request)
return redirect("/")
#return render(request, 'student/studentinfo.html', {} )
def order(request):
if request.method == 'POST':
form = 0
return render(request, 'student/orderform.html')
def dashboard(request):
user = request.user
return render(request, 'student/dashboard.html', {'user': user})
def blog(request):
return render(request, 'student/blog.html')
and this is my models.py, where UserInfo is:
from django.db import models
from django.contrib.auth.models import User
class UserInfo(models.Model):
user = models.ForeignKey(User)
class_of = models.IntegerField()
#username = user.username
#fname = user.first_name
#lname = user.last_name
#email = user.email
#Staff = user.is_staff
pub_date = models.DateTimeField( auto_now=True)
grade = models.IntegerField()
balance = models.DecimalField(max_digits=6, decimal_places=2)
class Events(models.Model):
name = models.CharField(max_length = 80)
date = models.DateTimeField()
cost = models.DecimalField(max_digits = 6, decimal_places = 2)
def __unicode__(self):
return str(self.name)
# Create your models here.
in my HTML code using the Django template language, {{ user.username }} and {{ user.email }} show up perfectly, but why won't {{ user.grade }} work the same way?
grade is not an attribute of Django's User model but is an attribute of UserInfo, you need need to use something like:
{{ user.user_infos.grade }}
Where user_infos is the related_name in your model (it should be OneToOneField right?):
user = models.OneToOneField(User, related_name='user_infos')

Profile() got an unexpected keyword argument 'name'

Edit : I am unable to load a image, but here is a link : https://plus.google.com/113782760013016224132/posts/3kcamT13yNP
Using Django. This is my first question.
I keep getting the error: Profile() got an unexpected keyword argument 'name'. I dont really understand why I am getting this error. It was working yesterday and now its all weird. Help would be much appreciated.
My forms.py is:
class RegistrationForm(ModelForm):
username = forms.CharField(label=(u'User Name'))
email = forms.EmailField(label=(u'Email Address'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
verifyPass = forms.CharField(label=(u'Verify Password'), widget=forms.PasswordInput(render_value=False))
class Meta:
model = Profile
exclude = ('user',)
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError("That username is already taken, please select another username.")
def clean(self):
password = self.cleaned_data.get('password', None)
verifyPass = self.cleaned_data.get('verifyPass', None)
if password != verifyPass:
#self.cleaned_data['password'] != self.cleaned_data['verifyPass']:
raise forms.ValidationError("Please try again, the passwords did not match.")
return self.cleaned_data
views.py:
def UserRegistration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile')
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username = form.cleaned_data['username'], email = form.cleaned_data['email'], password = form.cleaned_data['password'])
user.save()
users = Profile(user=user, name=form.cleaned_data['name'], date_of_birth=form.cleaned_data['date_of_birth'])
users.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('register.html', {'form': form}, context_instance=RequestContext(request))
else:
''' user is not submitting the form, show them a blank registration form '''
form = RegistrationForm()
context = {'form': form}
return render_to_response('register.html', context, context_instance=RequestContext(request))
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = LoginUserForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
users = authenticate(username = username, password = password)
if users is not None:
login(request, users)
return HttpResponseRedirect('/profile/')
else:
return render_to_response('login.html', {'form' : form}, context_instance = RequestContext(request))
else:
return render_to_response('login.html', {'form' : form}, context_instance = RequestContext(request))
else:
''' user is not submitting the form, show the login form '''
form = LoginUserForm()
context = {'form': form}
return render_to_response('login.html', context, context_instance=RequestContext(request))
def LogoutRequest(request):
logout(request)
return HttpResponseRedirect('/')
def Profile(request):
render_to_response('profile.html')
def home(request):
return render_to_response("home.html")
class LoginUserForm(forms.Form):
username = forms.CharField(label=(u'User Name'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
models.py:
class Profile(models.Model):
user = models.OneToOneField(User)
date_of_birth = models.DateField()
name = models.CharField(max_length=100)
def __str__(self):
return self.name

Categories