CSRF verification failed. Request aborted Django 1.6 - python

Trying to build a fashion technology application and as I am setting the forms, views, models and templates everything seems fine, and I get the CSRF verification failed error. Any clue as to what I am doing wrong?
models.py:
from django.db import models
from django.contrib.auth.models import User
class ProfileUser(models.Model):
user = models.OneToOneField(User,unique=True)
birthday = models.DateField(null=True,blank=True)
city = models.CharField(max_length=50,blank=True)
state = models.CharField(max_length=50,blank=True)
user_title = models.CharField(max_length=254, verbose_name="Influencer Level", blank=True)
user_points = models.IntegerField(null=False, verbose_name="Influence Credit", blank=True)
picture = models.ImageField(upload_to='images', blank=True)
#admin level and additional infomation
is_staff = models.BooleanField(default=False)
#Override the _unicode_() method to return out something meaningful
def _unicode_(self):
return self.user.username
forms.py:
#coding=utf-8
from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.forms import extras
from models import ProfileUser
###### Login for users ###########
# class LoginForm(forms.Form):
# username=forms.CharField(label=_(u"username"),max_length=30,widget=forms.TextInput(attrs={'size': 20,}))
# password=forms.CharField(label=_(u"password"),max_length=30,widget=forms.PasswordInput(attrs={'size': 20,}))
# class Meta:
# """docstring for Meta"""
# model = User
###### Registration for users ###########
class RegisterForm(forms.ModelForm):
email=forms.EmailField(max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Email', 'required':True}))
username=forms.CharField(max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Username','required':True}))
password=forms.CharField(max_length=30, widget=forms.PasswordInput(attrs={'placeholder': 'Password','required':True}))
password2=forms.CharField(max_length=30, widget=forms.PasswordInput(attrs={'placeholder': 'Re-Enter Password','required':True}))
class Meta:
"""The model that is extened from django models and the fields below are specified to prevent abstraction"""
model = User
fields = ('email', 'username', 'password', 'password2')
def clean(self):
cleaned_data = super(RegisterForm, self).clean()
email = cleaned_data.get('email')
username = cleaned_data.get('username')
password = cleaned_data.get('password')
password2 = cleaned_data.get('password2')
#check if username exist
user = User.objects.filter(username=username)
if user:
raise forms.ValidationError("this username is already exsist")
#check for password and re-enter password
if password != password2:
raise forms.ValidationError("Password does not match")
#check for email is system
emails = User.objects.filter(email=email)
if email:
raise forms.ValidationError("this email is already registered")
return cleaned_data
views.py:
#coding=utf-8
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login as auth_login ,logout as auth_logout
from django.utils.translation import ugettext_lazy as _
from forms import RegisterForm
from models import ProfileUser
###### Login for users ###########
# def login(request):
# template_var={}
# form = LoginForm()
# if request.method == 'POST':
# form = LoginForm(request.POST.copy())
# if form.is_valid():
# _login(request,form.cleaned_data["username"],form.cleaned_data["password"])
# return HttpResponseRedirect(reverse("login"))
# template_var["form"]=form
# return render_to_response("registration/login.html",template_var,context_instance=RequestContext(request))
# def _login(request,username,password):
# ret = False
# user = authenticate(username=username,password=password)
# if user:
# if user.is_active:
# auth_login(request,user)
# ret=True
# else:
# messages.add_message(request, messages.INFO, _(u'user is not active'))
# else:
# messages.add_message(request, messages.INFO, _(u'Incorrect username or password'))
# return ret
###### Registration for users ###########
def register(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('success'))
form = RegisterForm() # this will is used in the GET request
if request.method=="POST":
form=RegisterForm(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.is_active = True
user.save()
return redirect('base')
else:
return render_to_response("registration/signup.html",context_instance=RequestContext(request))
person = authenticate(
username=form.cleaned_data['username'],
password=form.cleaned_data['password']
)
login(request, person)
return HttpResponseRedirect(reverse("success"))
return render_to_response("registration/signup.html",context_instance=RequestContext(request))
Template:
{% extends 'home/base.html' %}
{% block title %}Signup with Indieitude{% endblock title %}
{% block search %}
{% endblock search %}
{% block space %}
<div class="space-registration"></div>
{% endblock space %}
{% block signup %}
<div id="content">
<div class="block">
<div class="box-login">
<div class="head">
<h2 class="heading-title">Start Discovering</h2>
<p align="center"><em>Log in with your Facebook</em>
</p>
</div>
<div class="socialconnect"> Log in with Facebook
</div>
<p align="center"><em>Or signup with your email & name</em>
</p>
<div class="box-form">
<form action="" method="post">{% csrf_token %}
<p>
{{form.email}}
</p>
<p>
{{form.username}}
</p>
<p>
{{form.password}}
</p>
<p>
<!-- <input type="password" id="" name="" required="required" class="text-input" placeHolder="Re-Enter Password" /> -->
</p>
<p class="agree">By signing up, I agree to Indieitude's Terms of Service & Privacy Policy
</p>
<p>
<input type="submit" name="submit" value="register" class="button large bold">
</p>
</form>
</div>
<div class="footer">
<h2 class="heading-title" align="center">Already have an account? Login</h2>
</div>
</div>
</div>
</div>
{% endblock signup %}

In views.py,
from django.core.context_processors import csrf
def register(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('success'))
if request.POST:
form=RegisterForm(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.is_active = True
user.save()
return redirect('base')
else:
form = RegisterForm()
args = {'form' : form}
args.update(csrf(request))
return render_to_response("registration/signup.html", args)

Related

django User matching query does not exist

i'm trying to signup with an otp for verification by sending email to the user mail, but getting this error, it's might be problem with signup.html, from where trying to get specific user otp to validate the data, if is there any better solution do this with django would be appreciate,
models.py
class User(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
is_buyer = models.BooleanField(default=False)
is_vendor = models.BooleanField(default=False)
objects = CustomUserManager()
def __str__(self):
return self.email
class UserOTP(models.Model):
user = models.ForeignKey(User, on_delete = models.CASCADE)
time_st = models.DateTimeField(auto_now = True)
otp = models.SmallIntegerField()
class Vendor(models.Model):
user = models.OneToOneField(User, related_name='vendor', on_delete=models.CASCADE)
business_name = models.CharField(max_length=50)
def __str__(self):
return self.user.email
forms.py
class VendorSignUpForm(UserCreationForm):
business_name = forms.CharField(required=True)
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
class Meta:
model = User
fields = ('business_name', 'email', 'password1', 'password2', )
#transaction.atomic
def save(self):
user = super().save(commit=False)
user.is_vendor = True
user.save()
customer = Vendor.objects.create(user=user)
customer.business_name=self.cleaned_data.get('business_name')
customer.save()
return user
views.py
def signup(request):
if request.method == 'POST':
get_otp = request.POST.get('otp')
print(get_otp)
if get_otp:
get_user = request.POST.get('user')
user = User.objects.get(email=get_user)
if int(get_otp) == UserOTP.objects.filter(user = user).last().otp:
user.is_active = True
user.save()
messages.success(request, f'Account is Created For {user.email}')
return redirect('login')
else:
messages.warning(request, f'You Entered a Wrong OTP')
return render(request, 'registration/signup.html', {'otp': True, 'user': user})
form = VendorSignUpForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email')
user = User.objects.get(email=email)
print(user)
user.email = email
user.is_active = False
user.save()
usr_otp = random.randint(100000, 999999)
UserOTP.objects.create(user=user, otp = usr_otp)
mess = f"Hello {user.email},\nYour OTP is {usr_otp}\nThanks!"
send_mail( 'Welcome to Costume Base - Verify Your Email',
mess , settings.DEFAULT_FROM_EMAIL, [user.email],
fail_silently = False)
return render(request, 'registration/signup.html', {'otp': True, user: user})
else:
form = VendorSignUpForm()
return render(request, 'registration/signup.html', {'form': form})
signup.html
{% block content %}
<div>
<h2>Signup</h2>
</div>
<div>
{% if otp %}
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom display">
<h3 class="float-left">Verify Your Email</h3>
</legend>
** is this input value showing the error? **
<input type="hidden" value="{{user.email}}" name = 'user' >
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">OTP</span>
</div>
<input type="text" class="form-control" placeholder="Enter Your OTP" aria-label="OTP"
aria-describedby="basic-addon1" name = 'otp'>
</div>
</fieldset>
<div class="form-grounp">
<button class="btn mainbtn" type="submit">Verify</button>
<small class="float-right text-muted"><i><a href="#" class="text-dark"
onclick="ReSendOTP('{{user.email}}', 'resendOTPmess')"><i id="resendOTPmess">Resend</i> OTP</a></small>
</div>
</form>
{% else %}
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<button type="submit">Register</button>
</form>
</div>
{% endif %}
{% endblock content %}
From the Django documentation:
This exception is raised by the ORM when an expected object is not found. For example, QuerySet.get() will raise it when no object is found for the given lookups.
That's probably due to one of your Model.get() methods, e.g:
user = User.objects.get(email=get_user)
Try to handle it with a try/catch or use a .filter() method instead of .get()

Collected user information is not saved in database using django framework

when I try to add details using this form it is not updating to my database.
please help me to solve this issue.
There is no error but the database is not updated.
club.html
{% extends "base.html" %}
{% block content %}
{%ifequal request.user.Isclubmember True%}
<div class='container'>
</div>
{%else%}
<div class="container">
<form action="." method="POST">
{%csrf_token%}
Profile Pic:
<input name="image" accept=".png,.jpg,.jpeg" type="file" value=selectimage>
Phonenumber:
<input name="userphonenumber" type="number" placeholder="+91 9876543210" >
<input type="submit" value="submit" class="btn btn-success">
</form>
</div>
{%endifequal%}
{% endblock content %}
views.py
from django.conf import settings
from django.contrib import messages
from django.shortcuts import redirect
from django.contrib.auth.models import User
from .models import UserProfile, Clubmember
from django.contrib.auth.models import User
from django.contrib.auth import login
from django.http import HttpResponseRedirect
def club(request):
if request.method == 'POST':
if request.user.is_authenticated:
Clubmember.user = request.user
Clubmember.phone_number = request.POST.get('userphonenumber')
Clubmember.userphoto = request.FILES.get('image')
request.user.Isclubmember = True
request.user.save()
Clubmember.save()
return redirect(request,'core:home')
else:
return redirect(request,'login_url')
else:
return render(request,'core:club')
models.py
class Clubmember(models.Model):
user = models.ForeignKey(UserProfile,default=1, on_delete=models.CASCADE)
userphoto = models.ImageField(upload_to="userphotos/%Y/%m",default=False)
phone_number = models.IntegerField(default=False)
usermoney = models.FloatField(default=0.0)
Change the view like this, it should work.
def club(request):
if request.method == 'POST':
if request.user.is_authenticated:
club_member = Clubmember()
club_member.user = request.user
club_member.phone_number = request.POST.get('userphonenumber')
club_member.userphoto = request.FILES.get('image')
request.user.Isclubmember = True
request.user.save()
club_member.save()
return redirect(request,'core:home')
else:
return redirect(request,'login_url')
else:
return render(request,'core:club')
and a better approach is
def club(request):
if request.method == 'POST':
if request.user.is_authenticated:
club_member = Clubmember(
user=request.user,
phone_number=request.POST.get('userphonenumber'),
userphoto=request.FILES.get('image')
)
club_member.save()
request.user.Isclubmember = True
request.user.save()
return redirect(request,'core:home')
else:
return redirect(request,'login_url')
else:
return render(request,'core:club')

Django - getting data from url in register view

Im trying to grab data from the url /register/?ref=123456 but having some trouble with it.
User registration is tied to one of my views:
class UserRegisterView(FormView):
form_class = UserRegisterForm
template_name = 'accounts/user_register_form.html'
success_url = '/accounts/login'
def form_valid(self, form):
username = form.cleaned_data.get('username')
email = form.cleaned_data.get('email')
password = form.cleaned_data.get('password')
new_user = User.objects.create(username=username, email=email)
new_user.set_password(password)
new_user.save()
ref = self.request.GET.get('ref', 'None')
print(ref)
return super(UserRegisterView, self).form_valid(form)
I'm trying to use "self.request.GET.get('ref', 'None')" to grab the data, but each time a user registers ref returns "None" rather than 123456
Here is the user_register_form.html:
<div class='row'>
<div class='col-sm-4 offset-sm-4 mt-3'>
<h1 class='text-center mt-3'>Sign Up</h1>
<form {% if form_id %} id='{{ form_id }}' {% endif %} class='form mt-3' method='POST' action=''>
{% csrf_token %}
{{ form|crispy }}
<input class='btn btn-primary-new' id="submit" type="submit" value="Sign Up" />
</form>
</div>
</div>
here's my solution guys:
I replaced
ref = self.request.GET.get('ref', 'None')
with
ref = (self.request.GET).dict()
data = ref['ref']
full implementation:
class UserRegisterView(FormView):
form_class = UserRegisterForm
template_name = 'accounts/user_register_form.html'
success_url = '/accounts/login'
def form_valid(self, form):
username = form.cleaned_data.get('username')
email = form.cleaned_data.get('email')
password = form.cleaned_data.get('password')
new_user = User.objects.create(username=username, email=email)
new_user.set_password(password)
new_user.save()
ref = (self.request.GET).dict()
data = ref['ref']
print(data)
return super(UserRegisterView, self).form_valid(form)

Django Form and Database

I am working width Django now. But I don't make sense about that.
I want to get id and password from the form and check if the password from form is correct to compare with the password of database.
Following are the my codes.
Please help me.
models.py
from django.db import models
class Doctor(models.Model):
doctor_id = models.CharField(max_length=16, primary_key=True)
clinic_id = models.ForeignKey(Clinic)
doctor_email = models.CharField(max_length=64)
doctor_password = models.CharField(max_length=32)
doctor_name = models.CharField(max_length=32)
create_date = models.DateTimeField(auto_now_add=True)
modify_date = models.DateTimeField(auto_now=True)
forms.py
from django import forms
from .models import Doctor
class LoginForm(forms.Form):
class Meta:
model = Doctor
fields = ('doctor_id', 'doctor_password',)
views.py
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .forms import LoginForm
from .models import Doctor
#ensure_csrf_cookie
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
_id = form.cleaned_data['doctor_id']
_password = form.cleaned_data['doctor_password']
b = Doctor.objects.all().filter(doctor_id=_id)
if _password is doctor_password:
login(request, user)
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'apiv1/login.html', {'form': form})
login.html
{% extends "base.html" %}
{% load staticfiles%}
{% block title%}Title{% endblock %}
{% block remoshincss %}/static/css/style.css{% endblock %}
{% block content %}
<div class="container">
<div align="center" class="imgtop"><img id="profile-img" class="profile-img-card" src="/static/img/remoshinlogo.png" /></div>
<div class="card card-container">
<p id="profile-name" class="profile-name-card"></p>
<form class="form-signin" action="{% url 'login' %}" method="post">{% csrf_token %}
<input type="user" id="userid" name="userid" class="form-control inputUser" placeholder="USER-ID" autofocus>
<input type="password" id="password" name="password" class="form-control inputPassword" placeholder="PASSWORD">
<input type="hidden" name="next" value="{{ next }}" />
<br>
<div align="center"><button style="width: 200px;" class="btn btn-lg btn-primary btn-block btn-signin" type="submit"><font color="#708090">Login</font></button></div>
</form>
</div>
</div>
{% endblock %}
Import check_password
from django.contrib.auth.hashers import check_password
check password
pass_ = check_password(_password, b.doctor_password)
if pass_ is False:
return HttpResponse('Invalid login')
Code:
#ensure_csrf_cookie
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
_id = form.cleaned_data['doctor_id']
_password = form.cleaned_data['doctor_password']
docter = Doctor.objects.filter(doctor_id=_id).last()
if docter is None:
return HttpResponse('Invalid login')
pass_ = check_password(_password, docter.doctor_password)
if pass_ is False:
return HttpResponse('Invalid login')
return HttpResponse('Authenticated successfully')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'apiv1/login.html', {'form': form})

Django if user.is_authenticated not working

I am just trying to run a simple {% if user.is_authenticated %} . But it always return False.
Here are my all the files.
views.py
from django.shortcuts import render_to_response, redirect
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.contrib.auth.hashers import *
from forms import UserLoginForm
from models import UserLogin
def index(request):
return render_to_response('index.html', context_instance = RequestContext(request))
def login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST or None)
if form.is_valid():
email_from_form = form.cleaned_data['email']
password_from_form = form.cleaned_data['password']
users = User.objects.filter(email = email_from_form)
for j in users:
if j.email == email_from_form:
pass_match = check_password(password_from_form, j.password)
if pass_match:
return redirect(reverse('profile'), context_instance = RequestContext(request))
else:
return HttpResponse('Entered password did not match')
else:
return HttpResponse('Entered email does not exist')
else:
return HttpResponse(form.errors)
else:
form = UserLoginForm()
return render_to_response('login.html', {'form':form}, context_instance = RequestContext(request))
def profile(request):
return render_to_response('profile.html', context_instance = RequestContext(request))
forms.py
from django import forms
class UserLoginForm(forms.Form):
email = forms.EmailField(max_length = 100)
password = forms.CharField(max_length = 100)
models.py
from django.db import models
class UserLogin(models.Model):
email = models.EmailField(max_length = 100)
password = models.CharField(max_length = 100)
def __unicode__(self):
return self.email
profile.html
<html>
<head>
<title>profile</title>
</head>
<body>
{% if user.is_authenticated %}
Welcome user, you are loged in..
{% else %}
You are not logged in
{% endif %}
</body>
</html>
login.html
<html>
<head>
<title>login</title>
</head>
<body>
<form action="{% url login %}" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" id="submit" name="submit" value="Login" />
</form>
</body>
</html>
It always returning You are not logged in
I am new to django and I dont understand this why it is like this.
You never log your user in. Try something along the following lines:
from django.contrib.auth import authenticate, login as auth_login
if request.method == 'POST':
form = UserLoginForm(request.POST or None)
if form.is_valid():
username = User.objects.get(email=form.cleaned_data['email'])
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user:
if user.is_active:
auth_login(request, user)
return HttpResponseRedirect(request.GET.get('next',
settings.LOGIN_REDIRECT_URL))
else:
error = 'Invalid username or password.'
Updated to use your form for clarity; error checking excluded.

Categories