Django if user.is_authenticated not working - python

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.

Related

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 login not working. Only works for superuser/admin

I was using django-registration-redux for my registration backend earlier and everything worked fine. I then decided to change the registration backend to django's default registration django.contrib.auth and the registration has been working fine but the login doesn't work. However, the thing is, only my superuser acoount can login, every other user can't login, both the regular users and the ones with staff clearance. It keeps giving me invalid username/password error.
Below is the login section of my views.py
def signin(request):
if request.user.is_authenticated:
return HttpResponseRedirect("/")
form = LoginForm()
errors = None
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
username = username.lower()
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
login(request, user)
if user.is_staff:
return redirect('sweet:vendor_index')
else:
return redirect('sweet:index')
else:
errors = "Invalid Username or Password"
return render(request, 'myregistration/signin.html', {'form':form, 'errors':errors})
Below is my signin.html
{% extends "base.html" %}
{% block title %}sign in{% endblock %}
{% block content %}
<h1>Sign in</h1>
{% if form.errors %}
<p class="error">Please correct the errors below:</p>
{{ errors }}
{% endif %}
<form method="post" action="{% url 'myregistration:signin' %}">{% csrf_token %}
<dl>
<dt><label for="id_username">Username:</label>{% if form.username.errors %} <span class="error">{{ form.username.errors|join:", " }}</span>{% endif %}</dt>
<dd>{{ form.username }}</dd>
<dt><label for="id_password">Password:</label>{% if form.password.errors %} <span class="error">{{ form.password.errors|join:", " }}</span>{% endif %}</dt>
<dd>{{ form.password }}</dd>
<dt><input type="submit" value="sign in" /></dt>
</dl>
</form>
<p>Forgotten password? Click here to reset password</p>
{% endblock %}
{% block content-related %}
<p>If you don't have an account, you can <a href="/accounts/register/">sign
up</a> for one.
{% endblock %}
And finally, my urls.py
from django.conf.urls import url
from myregistration import views
from django.contrib.auth import views as auth_views
app_name = 'myregistration'
urlpatterns = [
url(r'^register_vendor/', views.register_vendor, name='register_vendor'),
url(r'^register_customer/', views.register_customer, name='register_customer'),
url(r'^email_confirm/', views.email_confirm, name='email_confirm'),
url(r'^password_change/$', views.password_change, name='password_change'),
url(r'^password_reset/$', auth_views.password_reset, name='password_reset'),
url(r'^password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'),
url(r'^signin/', views.signin, name='signin'),
url(r'^logout/', views.logout, name='logout'),
url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'),
]
Below is my registration method
def register_customer(request):
registered = False
if request.method == 'POST':
customerform = CustomerSignUpForm(data=request.POST)
if customerform.is_valid():
customer = customerform.save(commit=False)
# Remeber to hash password again
customer.set_password(customer.password)
customer.is_active = False
customer.is_staff = False
customer.save()
text_content = "Account Activation Email"
mail_subject = "Activate your Juggernut account"
template_name = "myregistration/account_activate.html"
from_email = customerform.cleaned_data.get('email')
recipients = [customer.email]
kwargs = {
"uidb64":urlsafe_base64_encode(force_bytes(customer.pk)).decode(),
"token":account_activation_token.make_token(customer)
}
activation_url = reverse("myregistration:activate", kwargs=kwargs)
activation_url = "{0}://{1}{2}".format(request.scheme, request.get_host(), activation_url)
context = {
'customer':customer,
'activation_url':activation_url
}
html_content = render_to_string(template_name, context)
email=EmailMultiAlternatives(mail_subject, text_content, from_email, recipients)
email.attach_alternative(html_content, 'text/html')
email.send()
return redirect("myregistration:email_confirm")
registered=True
else:
print(customerform.errors)
else:
customerform = CustomerSignUpForm()
return render(request, 'myregistration/register_customer.html', {'customerform':customerform, 'registered':registered})
As you can see, in your views you have a form class to your view form = LoginForm(), but in your template you're not rendering this form and you won't be able to validate it and the line if form.is_valid(): will always return False.
You have two options, render the form class or change:
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
username = username.lower()
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
login(request, user)
if user.is_staff:
return redirect('sweet:vendor_index')
else:
return redirect('sweet:index')
else:
errors = "Invalid Username or Password"
to:
username = request.POST.get('username')
username = username.lower()
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
if user.is_staff:
return redirect('sweet:vendor_index')
else:
return redirect('sweet:index')
Probably the LoginForm class take another parameters and cannot be validated

Reverse for 'sending_message' not found. 'sending_message' is not a valid view function or pattern name

I have an app called com when I try to access viewing_user template which contains a form with action to another view get the error above
this is urls.py
app_name = 'com'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<name>[\w\-]+)/$',views.viewing_user, name='viewing_user'),
]
this is the views.py
from django.shortcuts import render
from django.contrib.auth.models import User
# Create your views here.
RECEIVER_ID = 0
def index(request):
return render(request, 'com/index.html',{})
def viewing_user(request, name):
#username = request.GET.get('username','')
try:
User_obj = User.objects.get(username = name)
RECEIVER_ID = User_obj.id
except User.DoesNotExist:
User_obj = None
return render(request, 'com/viewing_user.html',{'u':name,'obj':User_obj})
def sending_message(request):
form = MessageForm()
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid:
message = message_form.save(commit = False)
message.date = datetime.date.now()
message.from_user = user.id
message._to = RECEIVER_ID
message.save()
else:
print form.errors
return render(request, 'com/viewing_user.html', {'form':form})
this is the template vieweing_user.html which seems that has a problem in the action of the form
<html>
{% if obj == None %}
<h2>Sorry this user ({{u}}) DoesNotExist</h2>
{% else %}
<h3>Be honest, and Tellme what you want</h3>
<br>
<i>{{obj.username}}</i>
<form method="post" action="{%url 'com:sending_message' %}">
{%csrf_token%}
{% for hidden in form.hidden_fields%}
{{hidden}}
{%endfor%}
{% for visible in form.visible_fields%}
{{visible}}
{%endfor%}
<input type="submit" value='Tell'/>
</form>
{%endif%}
</html>
reverse tries to look for its parameter value in urlpatterns. You do not have any url pattern with name sending_message in com namespace.
You would want to create an url pattern with name sending_message
url(r'^(?Psomepattern)/$',views.sending_message, name='sending_message'),

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})

CSRF verification failed. Request aborted Django 1.6

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)

Categories