Username and password authentication in django - django

I need to validate username and password in django app, below are the details
view is,
class HomeView(TemplateView):
template_name = 'home.html'
template_name2 = 'Logout.html'
def get(self,request):
form = LoginForm()
posts=users_data.objects.all()
args = {'form': form, 'posts': posts}
return render(request, self.template_name, args)
return render(request,self.template_name, {'form':form})
#template_name2 = 'Welcome.html'
def post(self,request):
form = LoginForm(request.POST)
if form.is_valid():
#text=form.cleaned_data['post']
username = forms.cleaned_data.get("Username")
password = forms.cleaned_data.get("Password")
user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError("This user does not exist")
return render(request, self.template_name1)
else:
form.save()
return render(request, self.template_name2)
else:
return render(request, self.template_name1)
after entering username and password it is giving me error and doing nothing. I am stuck at this point . Requesting for help.
my form is,
from django import forms
from login.models import *
from django.contrib.auth import authenticate,login,logout,get_user_model
user=get_user_model()
class SignupForm(forms.ModelForm):
class Meta:
model=users_data
fields=('Name','Email','Username','Password')
class LoginForm(forms.ModelForm):
class Meta:
model=users_data
fields=('Username','Password')
def clean(self):
username = self.cleaned_data.get("Username")
password = self.cleaned_data.get("Password")
user=authenticate(username=username,password=password)
if not user:
raise forms.ValidationError("This user does not exist")

You can use get user input from LoginForm this code blog.
username = form.cleaned_data.get("Username")
password = form.cleaned_data.get("Password")

Related

Django user.is active

Why when i desactive user on Django admin site in my class in post method
requirement return negative first if requirement user is not None ?
Probably if user desative true Django don`t look him in user table ?
class LoginView(View):
template_name = 'login.html'
def get(self, request):
form = LoginForm()
return render(request, self.template_name, locals())
def post(self, request):
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('home')
else:
alert = messages.error(request, 'Twoje konto zostało zablokowane!')
return render(request, self.template_name, locals())
else:
alert = messages.error(request, 'Błędna nazwa użytkownika!')
return render(request, self.template_name, locals())
In authenticate function, django call authenticate on your AUTHENTICATION_BACKENDS in settings.py.
ModelBackend is a default authentication backend that has been provided by Django, and if you are using it, it checks if user is acive or not. It's sth like this:
def user_can_authenticate(self, user):
"""
Reject users with is_active=False. Custom user models that don't have
that attribute are allowed.
"""
is_active = getattr(user, 'is_active', None)
return is_active or is_active is None

model form has no attribute 'cleaned_data'

I want to sign in to be able to use the site. However, I'm having a problem: 'LoginForm' object has no attribute 'cleaned_data'. Please tell me how can I solve it. I apologize in advance for my English
My forms.py
class LoginForm(forms.Form):
user_name = forms.CharField(max_length=20, widget=TextInput(attrs={'type':'text','class': 'form-control','placeholder': 'Input username'}))
passWord = forms.CharField(max_length=25, widget=TextInput(attrs={'type':'password','class': 'form-control','placeholder': 'Input password'}))
class Meta:
fields = ['user_name', 'passWord']
My views.py
def login_view(request):
template_name = 'main/login.html'
action_detail = ''
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid:
username = form.cleaned_data.get('user_name')
password = form.cleaned_data.get('passWord')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('/')
else:
action_detail = 'invalid username or password'
else:
form = LoginForm()
context={
'title': 'Login',
'form': form,
'action_detail': action_detail,
}
return render(request, template_name, context)
is_valid is a function.
https://docs.djangoproject.com/en/4.0/ref/forms/api/#django.forms.Form.is_valid
You should call it.
if form.is_valid():

How can i create a login view after registration?

I create models,forms and views for registrarion and i want to create a login view so that after registration user can login.
models.py
from django.contrib.auth.models import AbstractUser
from django_countries.fields import CountryField
g_CHOICES = (('male','male'),('female','female'))
class User(AbstractUser):
gender = models.CharField(max_length=100,choices=g_CHOICES,default="male")
country = CountryField()
location = models.CharField(max_length=30, blank=True)
forms.py
g_CHOICES = (('male','male'),('female','female'))
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
gender = forms.ChoiceField(choices=g_CHOICES)
country = CountryField().formfield()
location = forms.CharField(max_length=30,)
class Meta:
model = User
fields = ['first_name','last_name','username','email',
'password1','password2','gender',
'country','location']
views.py
def register(request):
if request.method == 'POST':
rform = UserRegisterForm(request.POST)
if rform.is_valid():
rform.save()
username = rform.cleaned_data.get('username')
messages.success(request,('Account created for '+str(username)))
return redirect('/')
else:
rform = UserRegisterForm()
return render(request,'reg.html',{'rform':rform})
Now i want to create a view for login please someone help
You need a view that takes the user's username and password from the POST request, then authenticates them and logs them in using 'authenticate' and 'login' from django.contrib.auth package.
from django.contrib.auth import login, authenticate
from django.views import View
class HandleLogin(View):
def get(self, request):
return render(request, "login.html", {})
def post(self, request):
username= request.POST.get("username")
password = request.POST.get("password")
user = authenticate(username, password)
if user is not None:
if user.is_active:
login(request, user)
# Do something for succesfull logged in
else:
# Do something else because user is not active
else:
# Do something about user not existing
For more information: https://docs.djangoproject.com/en/2.2/topics/auth/default/
You can use something like below one:
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
messages.success(request, 'You are now logged in')
return redirect('dashboard')
else:
messages.error(request, 'Invalid credentials')
return redirect('login')
else:
return render(request, 'accounts/login.html')
Or if you are using a django form you can do this way too and this is more preferred way:
def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(request,
username=cd['username'],
password=cd['password'])
if user is not None:
login(request, user)
return HttpResponse('Authenticated '\
'successfully')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'account/login.html', {'form': form})

Django form meta and validation

I have form:
class FindAdvert(forms.ModelForm):
class Meta:
model = Advert
fields = ('id', 'code')
But in this way I can't 'login' because validation return error: id already exist.
How modify this form to allow 'login' (instead of registration)?
You don't need ModelForm for login, because it's semantical goal - create|edit database data (anyway you can hardcode id in your view - but it is wrong way).
So create simple Form with custom validation rules (in clean method or in your views), something like that below:
class LoginForm(forms.Form):
username = forms.CharField(
label=u'Username',
required=True,
)
password = forms.CharField(
label=u'Password',
required=True,
widget=forms.PasswordInput
)
def clean(self):
cleaned_data = super(LoginForm, self).clean()
username = cleaned_data.get('username')
password = cleaned_data.get('password')
if (username and password and User.objects.filter(username=username).count() == 0)\
or (username and password and User.objects.filter(username=username).count() == 1 and
User.objects.get(username=username).password != password):
raise forms.ValidationError(u'Wrong username or password')
return cleaned_data
views:
from django.contrib.auth import logout, authenticate, login
from django.views.generic import FormView, RedirectView
# ...
class LoginFormView(FormView):
template_name = 'common/login.html'
form_class = LoginForm
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
logout(request)
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_superuser:
login(request, user)
return self.form_valid(form)
else:
return self.form_invalid(form)
def get_success_url(self):
return self.request.GET.get('next') or reverse('human:add')
class LogoutRedirectView(RedirectView):
permanent = False
def get_redirect_url(self, *args, **kwargs):
logout(self.request)
return reverse('common:login')

Editing a userprofile on django

How to create a userprofile editable page and upon clicking submission it updates the details provided during registration(the details stored in the database) using DJANGO?.
Creation of registration form for a user, and like i have said in my opening post, i want the user after he must have logged in to able to edit what he provided during registration and it will update the previous details stored in the database.
I know i need to create a view for it, but have not arrived at how to call on the details provided during registration. Well maybe using user.get_profile()
forms.py
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from registeredmember.models import Registeredmember
class RegistrationForm(ModelForm):
first_name = forms.CharField(label=(u'First Name'))
middle_name = forms.CharField(label=(u'Middle Name'))
last_name = forms.CharField(label=(u'Last Name'))
occupation = forms.CharField(label=(u'Occupation'))
income = forms.IntegerField(label=(u'Income Amount'))
age = forms.IntegerField(label=(u'Age'))
address_line1 = forms.CharField(label=(u'Address line 1'))
address_line2 = forms.CharField(label=(u'Address line 2'))
city = forms.CharField(label=(u'City'))
state = forms.CharField(label=(u'State'))
phone_no_Mobile = forms.IntegerField(label=(u'Phone Number (Home)'))
phone_no_Work = forms.IntegerField(label=(u'Phone Number (Work)'))
purpose = forms.CharField(label=(u'Purpose'))
username = forms.CharField(label=(u'Username'))
email = forms.EmailField(label=(u'Email Address'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput)
password1 = forms.CharField(label=(u'Verify Password'), widget=forms.PasswordInput)
class Meta:
model = Registeredmember
exclude = ('user','reference_number',)
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.')
def clean_email(self):
email = self.cleaned_data['email']
try:
User.objects.get(email=email)
except User.DoesNotExist:
return email
raise forms.ValidationError('That email address is already in the database, please provide another.')
class LoginForm(forms.Form):
username = forms.CharField(label=(u'Username'),widget=forms.TextInput(attrs={'size': '30'}))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput)
views.py
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from registeredmember.forms import RegistrationForm, LoginForm
from registeredmember.models import Registeredmember
from django.contrib.auth import authenticate, login, logout
import random, time
from random import randint
def userregistration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = RegistrationForm
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.first_name = form.cleaned_data['first_name']
user.last_name = form.cleaned_data['last_name']
user.save()
registeredmember = Registeredmember(user=user, prefix = form.cleaned_data['prefix'],first_name=form.cleaned_data['first_name'],\
middle_name=form.cleaned_data['middle_name'],last_name=form.cleaned_data['last_name'],gender=form.cleaned_data['gender'],\
occupation=form.cleaned_data['occupation'],income=form.cleaned_data['income'],age=form.cleaned_data['age'],\
address_line1=form.cleaned_data['address_line1'],address_line2=form.cleaned_data['address_line2'],city=form.cleaned_data['city'],\
state=form.cleaned_data['state'],phone_no_Mobile=form.cleaned_data['phone_no_Mobile'],phone_no_Work=form.cleaned_data['phone_no_Work'],\
purpose=form.cleaned_data['purpose'])
registeredmember.save()
return render_to_response('carloan/regsuccessful.html',{'ref_no': ref_no}, context_instance=RequestContext(request))
else:
return render_to_response('carloan/register.html', {'form': form}, context_instance=RequestContext(request))
else:
'''user is not submitting the form, show them a blank registration form'''
form = RegistrationForm()
return render_to_response('carloan/register.html', {'form': form}, context_instance=RequestContext(request))
#login_required
def Profile(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
registeredmember = request.user.get_profile
return render_to_response('carloan/profile.html', {'registeredmember': registeredmember}, context_instance=RequestContext(request))
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method =='POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
registeredmember = authenticate(username=username, password=password)
if registeredmember is not None:
login(request, registeredmember)
return HttpResponseRedirect('/profile/')
else:
return render_to_response('carloan/loginerror.html', context_instance=RequestContext(request))
else:
'''user is submitting a blank login form, notify him that he submitted a blank form'''
return render_to_response('carloan/loginblank.html', context_instance=RequestContext(request))
else:
'''user is not submitting the form, show the login form'''
form = LoginForm()
return render_to_response('carloan/login.html',{'form': form}, context_instance=RequestContext(request))
def LogoutRequest(request):
logout(request)
return render_to_response('carloan/logout.html', context_instance=RequestContext(request))
The code below gives the error username already exists, but when i specify a new username it updates although it doesn't update the username but the other fields
views.py for the editprofile
#login_required
def editprofile(request):
registeredmember = request.user.get_profile()
if request.method == 'POST':
userprofile_edit = RegistrationForm(request.POST, instance = registeredmember)
if userprofile_edit.is_valid():
userprofile_edit.save()
return HttpResponseRedirect('/profile/')
else:
userprofile_edit = RegistrationForm(instance = registeredmember)
return render_to_response('carloan/editprofile.html', {'userprofile_edit': userprofile_edit}, context_instance=RequestContext(request))
Got it sorted out with codes below:
forms.py
class EditForm(forms.ModelForm):
class Meta:
model = Registeredmember
exclude = ('user','username','email','password','password1',)
views.py
#login_required
def editprofile(request):
if request.method == 'POST':
userprofile_edit = EditForm(request.POST, instance = request.user.get_profile())
if userprofile_edit.is_valid():
userprofile_edit.save()
return HttpResponseRedirect('/profile/')
else:
userprofile_edit = EditForm(instance = request.user.get_profile())
return render_to_response('carloan/editprofile.html', {'userprofile_edit': userprofile_edit}, context_instance=RequestContext(request))
Thank you all...
Django 1.5 and custom user models will help with this, but in the mean time your ModelForm set up is fine.
To initialize a ModelForm from an instance of its object, do this:
user_profile_form = RegistrationForm(request.POST, instance=request.user.get_profile())
The request.POST in that line allows you to update the user_profile_form object with the user's input. It will nicely merge the existing data from your instance with the new info from the user.
You can then print this to a view, or you can save it doing this:
if user_profile_form.is_valid():
user_profile_form.save()
else
# do other stuff