User' object has no attribute 'make_password' - django

what is the error with set_password
/base/backends.py in authenticate
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class CaseInsensitiveModelBackend(ModelBackend):
def authenticate(self,request,username=None,password=None,**Kwargs):
UserModel=get_user_model()
if username is None:
username=Kwargs.get(UserModel.USERNAME_FIELD)
try:
case_insensitive_username_field='{}__iexact'.format(UserModel.USERNAME_FIELD)
user = UserModel._default_manager.get(**{case_insensitive_username_field:username})
except UserModel.DoesNotExist:
UserModel().set_paassword(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user
i try to put make_password but not working

Related

How to get individual users data after login in django?

iam new to django.Can anyone send me the code of signup and login page to get particular details of the username without using django.contrib.auth.models import User.
(i.e if we login with some usename then it should only give details of that username not remaining).
Find view you want manipulate user in, declare user like current_user = request.user. I will provide you my login and register views below. In examples shown below I had from django.contrib.auth.models import User, but you can modify it as shown above.
Register:
def registerPage(request):
if request.user.is_authenticated:
return redirect('todoapp:home')
else:
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
email = request.POST.get('email')
if form.is_valid():
if check_does_email_already_exist(email):
form.save()
messages.success(request, "User is registered sucessfully")
return redirect('todoapp:login')
else:
messages.warning(
request, "User with same email already exist")
else:
messages.warning(
request, "That username already exist or your password is too short")
context = {
'form': form,
}
return render(request, 'register.html', context)
Login:
def loginPage(request):
if request.user.is_authenticated:
return redirect('todoapp:home')
else:
if request.method == 'POST':
username = request.POST.get('uname')
password = request.POST.get('passwd')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('todoapp:home')
else:
messages.warning(
request, "Your password or username isn't valid")
return redirect('todoapp:login')
else:
pass
return render(request, 'login.html')
These are my imports:
from django.shortcuts import render, redirect
from django.urls import reverse
from django.utils import timezone
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.shortcuts import get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import CreateUserForm
And this is my forms.py:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from django.forms import fields
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = [
'username',
'email',
'password1',
'password2',
]
I hope my answer will help you.

How to authenticate for login

How I can authenticate my user for login ,here authenticate does not work properly
I have used authenticate for login
views.py
from django.shortcuts import render
from basic_app.models import Signup
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponse,HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
def signup(request):
if request.method=="POST":
obj=Signup()
obj.username=request.POST.get('username')
obj.password=request.POST.get('password')
obj.save()
context={'username':'username'}
return render(request,'basic_app/singup.html',context)
else:
return render(request,'basic_app/singup.html')
def login(request):
if request.method=="POST":
username=request.POST.get('username')
password=request.POST.get('password')
user=authenticate(username=username,password=password)
if user:
login(request,user)
return HttpResponse("you have login")
else:
return HttpResponse("wrong password or username")
else:
return render(request,'basic_app/login.html')
You should login using login after authenticating.
user = authenticate(username=request.POST.get('username',''),
password=request.POST.get('password',''))
login(request, user)
Read:https://docs.djangoproject.com/en/2.1/topics/auth/default/#how-to-log-a-user-in
Actually, you can use Django's inbuilt LoginView ("https://docs.djangoproject.com/en/2.1/topics/auth/default/#django.contrib.auth.views.LoginView")
If you want to change the layout style. Either override the Django login template or override the class view.
For overriding the class view:
from django.contrib.auth.views import LoginView
class MySignInView(LoginView):
form_class = MySignInForm
template_name = 'mylife/myrules/login.html'
I have edited your following code :
from django.shortcuts import render
from basic_app.models import Signup
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponse,HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
def login(request):
if request.method=="POST":
username=request.POST.get('username')
password=request.POST.get('password')
user=authenticate(username=username,password=password)
if user:
login(request,user)
return HttpResponse("you have login")
else:
return HttpResponse("wrong password or username")
else:
return render(request,'basic_app/login.html')
1) When you authenticate your username and password, it just returns User and it doesn't make you to login,
2) for login you have to call login(requst,user),it will create session in your database as acknowledgment

how to login a user using forms?

forms.py:
from django import forms
from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.utils.text import capfirst
from .models import Classname, Sectionname, Teachername, Attendancename
class AuthenticationForm(forms.Form):
username = forms.CharField(max_length=20)
password = forms.CharField(widget=forms.PasswordInput)
error_messages = {
'invalid_login': ("Please enter a correct %(username)s and password."
"Note that both fields may be case-sensitive."),
'inactive': ("This account is inactive"),
}
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if username and password:
self.user_cache = authenticate(username=username, password=password)
if self.user_cache is None:
raise forms.ValidationError(
self.error_messages['invalid_login'],
code='invalid_login',
)
else:
self.confirm_login_allowed(self.user_cache)
return self.cleaned_data
def confirm_login_allowed(self, user):
if user.is_active:
login(self.user) /** It raises error here... **/
else:
raise forms.ValidationError(
self.error_messages['inactive'],
code='inactive',
)
def get_user_id(self):
if self.user_cache:
return self.user_cache.id
return None
def get_user(self):
return self.user_cache
views.py:
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.template.response import TemplateResponse
from django.views.generic import DeleteView, ListView
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.cache import never_cache
from .models import Classname, Sectionname, Teachername, Attendancename
from .forms import ClassnameForm, SectionnameForm, TeachernameForm, AttendancenameForm, UserForm, PasswordChangeForm, AuthenticationForm
def user_login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse('student:mains'))
else:
print(form.errors)
else:
form = AuthenticationForm()
return render(request, 'login.html', {'form': form},)
urls.py:
from django.conf.urls import url, patterns
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.user_login, name='login'),
url(r'^logout/$', views.user_logout, name='logout'),
url(r'^password_change/$', auth_views.password_change, {'template_name': 'password_change_form.html', 'post_change_redirect': '/stu/password_change/done/'}, name="password_change"),
url(r'^password_change/done/$', auth_views.password_change_done, {'template_name': 'password_change_done.html'}, name="password_change_done"),
url(r'^restricted/', views.restricted, name='restricted'),
url(r'^mains/', views.mains, name = 'mains'),
]
I'm new to django authentication. I'm trying to make things as per the docs I have read. As your see above I've a 'user_login' view and 'AuthenticationForm' form.
I'm tring to login the user, but don't know the way how to do it? As I tried it in my view but didn't worked.
Then I tried it in my 'can_login_allowed' form's method but doesn't work.
Is there any other method to implement it?
Please! Can Anybody help me to fix it?
Thanks in Advance....
The login function takes request as first parameter. So you have write confirm_login_allowed like this:
def confirm_login_allowed(self, request):
if self.user_cache.is_active:
login(request,self.user_cache)
else:
raise forms.ValidationError(
self.error_messages['inactive'],
code='inactive',
)
And call it in the view like this
def user_login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
form.confirm_login_allowed(request)
return HttpResponseRedirect(reverse('student:mains'))
else:
....
Also don't call the confirm_login_allowed method from clean method because it does't have the request.

Django: TypeError: 'username' is an invalid keyword argument for this function

I have a model called Employee for the registration. When I run the code I go the
username' is an invalid keyword argument for this function
error.
employee=Employee(user=user, username= form.cleaned_data['username'], email= form.cleaned_data['email'], password=form.cleaned_data['password'])
this is my view.py code
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from django.template import RequestContext
from Employee_Details.forms import RegistationForm
from Employee_Details.models import Employee
def EmployeeRegistation(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method=='POST':
form=RegistationForm(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()
employee=Employee(user=user, username= form.cleaned_data['username'],email= form.cleaned_data['email'],password=form.cleaned_data['password'])
employee.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('registation.html',{"form":form}, context_instance=RequestContext(request))
else:
'''user is not submitting the form show a blank Registation Form'''
form=RegistationForm();
context={'form':form}
return render_to_response('registation.html',context,context_instance=RequestContext(request))
This is my model:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class Employee(models.Model):
user=models.OneToOneField(User)
name=models.CharField(max_length=100)
address=models.CharField(max_length=200)
designation=models.CharField(max_length=100)
email=models.CharField(max_length=100)
role=models.CharField(max_length=10)
#image=models.ImageField()
project=models.CharField(max_length=50)
task=models.CharField(max_length=50)
def __unicode(self):
return self.name
This is my form.py
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from Employee_Details.models import Employee
class RegistationForm(ModelForm):
username=forms.CharField(label=(u'User Name'))
email=forms.EmailField(label=(u'Email Address'))
password=forms.CharField(label=(u'Password'))
password1=forms.CharField(label=(u'Verfy Password'))
name=forms.CharField(label=(u'Name'))
address=forms.CharField(label=(u'Address'))
designation=forms.CharField(label=(u'Designation'))
role=forms.CharField(label=(u'Role'))
#image=models.ImageField()
project=forms.CharField(label=(u'Project'))
task=forms.CharField(label=(u'Task'))
class Meta:
model=Employee
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('The username is already taken. Please try with another')
def clean(self):
if self.cleaned_data['password'] !=self.cleaned_data['password1']:
raise forms.ValidationError("The Password did not match. Please try again")
return self.cleaned_data
please someone help help me to resolve this matter. I’m referring some video tutorials.
You have no username field in your model and it's redundant because you have that field already in the User model:
user=User.objects.create_user(username=form.cleaned_data['username'],email= form.cleaned_data['email'],password=form.cleaned_data['password'])
user.save()
employee=Employee(user=user, email=form.cleaned_data['email'], password=form.cleaned_data['password'])
(...)
try modelformset_factory instead!

lookup usernames

I am working on creating a page for each user, how do i lookup a username in my django user model
views.py
def user_page(request,user):
user = User.objects.filter(user =user.username)
return render_to_response('user_page.html',"user":user,context_instance=RequestContext(request))
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
def user_page(request, username):
user = get_object_or_404(User, username=username)
return render_to_response('user_page.html',{"user":user},context_instance=RequestContext(request))
def user_page(request,username):
user = User.objects.filter(username=username)
return render_to_response('user_page.html',{"user":user},context_instance=RequestContext(request))