Django user.is active - django

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

Related

Django Custom Authentication Backend does not work

I've made a user model with USERNAME_FIELD defined as phone_number. So login form requires phone_number and password. I want users to be able to also login through their emails. So I created an authentication backend class. Users can login with their phone numbers but they canbot do so with their emails and will receive the 'Username and/or password is wrong' message.
authentication.py:
from django.contrib.auth import get_user_model
class CustomAuthBackend:
def authenticate(self, username=None, password=None):
try:
user = get_user_model().objects.get(email=username)
if password:
if user.check_password(password):
return user
return None
except:
return None
def get_user(self, user_id):
try:
user = get_user_model().objects.get(pk=user_id)
return user
except:
return None
forms.py:
class UserLoginForm(forms.Form):
username = forms.CharField(label="Phone Number / Email")
password = forms.CharField(widget=forms.PasswordInput(), label="Password")
views.py:
class UserLogin(View):
form_class = UserLoginForm
template_name = "accounts/login.html"
def get(self, request):
return render(request, self.template_name, {"form": self.form_class})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(
request, username=cd["username"], password=cd["password"]
)
if user:
login(request, user)
messages.success(request, "Logged in successfully.", "success")
return redirect("home:home")
else:
messages.error(request, "Username and/or password is wrong.", "danger")
return render(request, self.template_name, {"form": form})
messages.error(request, "Login failed", "danger")
return render(request, self.template_name, {"form": form})
settings.py:
AUTHENTICATION_BACKENDS = [
"django.contrib.auth.backends.ModelBackend",
"accounts.authentication.CustomAuthBackend",
]
Assuming that you have already included the custom backend in AUTHENTICATION_BACKENDS setting in settings.py file.
You can make a condition check that whether it is a phone no. or email using regex so:
import re
from django.contrib.auth import get_user_model
class CustomAuthBackend:
def authenticate(self, request, username=None, password=None):
UserModel = get_user_model()
# Check whether username is an email address or phone number
if re.match(r'^\+?\d{10,14}$', username):
try:
user = UserModel.objects.get(phone_number=username)
if user.check_password(password):
return user
except UserModel.DoesNotExist:
return None
else:
try:
user = UserModel.objects.get(email=username)
if user.check_password(password):
return user
except UserModel.DoesNotExist:
return None
def get_user(self, user_id):
try:
return get_user_model().objects.get(pk=user_id)
except get_user_model().DoesNotExist:
return None
I had forgotten to include request as a parameter in authenticate method. :)
Correct version:
def authenticate(self, request, username=None, password=None):
# ...

Authenticate with only username

I creating quiz app, in which user login with only username and the proceed for a quiz but django authenticate not working
views.py
class UserFormView(View):
form_class = UserForm
template_name = 'app/registration_form.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
# cleaned data
username = form.cleaned_data['username']
user.save()
# autheticate
user = authenticate(username=username)
if user is not None:
if user.is_active:
login(request, user)
return redirect('app:quiz_list')
else:
return HttpResponse('active nahi hai')
else:
return HttpResponse('pehchan me nahi hai')
return render(request, self.template_name, {'form': form})
If you are using default authentication backend it requires username and password
You can create a custom authentication backend yourself by following related documentation
Considering you are not really authenticating you can just filter user from database and use login function afterwards
#TODO add exception if there is no user with username
user = User.objects.filter(username=username).get()
login(request, user)

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

Username and password authentication in 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")

Setting custom user object in context processor in django

I have a custom user model. After doing successful login, I am getting the anonymous user in HttpResponseRedirect and templates as well. How do I get the logged in user?
Login View:
class LoginFormView(View):
form_class = UserLoginForm
user_model = get_user_model()
template_name = 'account/login.html'
def get(self, request, *args, **kwargs):
form = self.form_class
return render(request, self.template_name, {'form':form})
def post(self, request, *args, **kwargs):
email = request.POST['email']
password = request.POST['password']
user = authenticate(email=email, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('home'))
else:
messages.error(request, 'Please enter correct email and password!')
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
If you have the request template context processor enabled, you'll be able to access the user in the template with {{ request.user}}.
Secondly, make sure you are importing the login function and not the login view. It should be:
from django.contrib.auth import login