Cant login to created user after using custom model - django

from django.db import models
from django.contrib.auth.models import AbstractUser,User
from django.utils.html import escape,mark_safe
# Create your models here.
class user(AbstractUser):
is_admin = models.BooleanField(default=False)
is_teacher = models.BooleanField(default=False)
is_student = models.BooleanField(default=False)
def login_view(request):
form = AuthenticationForm()
if request.method=='POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username,password=password)
if user.is_admin==True:
login(request,user)
return HttpResponse(f"Welcome {username}")
else:
return HttpResponse('failled')
return render(request, 'login.html', {'form': form})
cant login using the user created by superuser.
the user is creating but while calling it or using it shows
created a user with staff and superuser authorization
still cant login

I think you need to set the setting AUTH_USER_MODEL. Also, not sure why you're overriding the login view. You can use another setting LOGIN_REDIRECT_URL to set the URL where the user gets redirected on successful login.

You need to unregister the built-in User from the admin and then register your own user model in admin.py
Example in the docs
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from customauth.models import user
admin.site.register(user, UserAdmin)
# admin.site.unregister(User)
You may have to subclass the UserChangeForm to add your custom fields

Related

How to Verify Email in Django using OTP and UserCreationForm

I am creating a Quiz App. In that I have a sign up page for user authentication which is using the default User Model and User CreationForm. I want to add a email verification in it by sending a otp on the email.
Please explain me how can I send otp on email using default user model and user creation form to verify the otp on the email.
My user app code is:
forms.py
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
email = forms.EmailField()
class Meta:
model = get_user_model()
fields = ['username', 'email', 'password1', 'password2']
views.py
import pyotp
from django.contrib.auth.models import User
from .forms import UserRegisterForm
from django.contrib import messages
from django.shortcuts import render, redirect
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
otp=pyotp.totp('base32secret3232')
form.save()
messages.success(request, f'Account Created for {User.username}. You can Login')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
You can refer below article.
https://medium.com/analytics-vidhya/how-to-implement-otp-based-authentication-on-django-rest-framework-185ae8032f07#:~:text=Step%201%3A%20Find%20that%20phone,the%20authenticity%20of%20the%20user.

After creating a custom model for custom roles now if create a user and give him 'admin' authentication i cant login to admin page

from django.db import models
from django.contrib.auth.models import AbstractUser,User
from django.utils.html import escape,mark_safe
# Create your models here.
class user(AbstractUser):
is_admin = models.BooleanField(default=False)
is_teacher = models.BooleanField(default=False)
is_student = models.BooleanField(default=False)
def login_view(request):
form = AuthenticationForm()
if request.method=='POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username,password=password)
if user.is_admin==True:
login(request,user)
return HttpResponse(f"Welcome {username}")
else:
return HttpResponse('failled')
return render(request, 'login.html', {'form': form})
now if i create a user and give him any of these privilege and then call the user anywhere
it shows
'NoneType' object has no attribute 'is_admin'

Django-registration - How to check if email exists in database

During registration currently when a user is entering an existing username and an email it is notified that this username already exists in database. When the user enters a different username but an email that exists then user is created successfully in db.
So i want to validate if email exists in database. For this reason i've created the following but unfortunately it does not work as expected, (user is created if same email exists).
forms.py file
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
class SignupForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
def clean_email(self):
# Get the email
email = self.cleaned_data.get('email')
if User.objects.filter(email__iexact=email).exists():
raise forms.ValidationError("User with that email already exists")
return email
views.py file
from django.shortcuts import render
from django.contrib.messages.views import SuccessMessageMixin
from django.views import generic
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from .forms import SignupForm
class UserRegisterView(SuccessMessageMixin, generic.CreateView):
form_class = SignupForm
template_name = 'registration/register.html'
success_url = reverse_lazy('login')
success_message = "Hello %(username)s! Your account has been created"
Thank you for your time.
Because you took email as a dictinobary <'dict' object is not callable>
so, as a list. It is working on my project
email = self.cleaned_data.get['email']
def clean_email(self):
# Get the email
email = self.cleaned_data.get['email']
if User.objects.filter(email__iexact=email).exists():
raise forms.ValidationError("User with that email already exists")
return email

form.is_valid() returns False and the login() function doesn't work

I'm trying to login a user who was previously registered in a database, but the form.is_valid() returns False and the login() function doesn't work. I extended the User class with a Client class that is inheriting from User, and I think this is what is causing the issue, because I tried almost the same code before, but without the extended User class, and it worked perfectly. What am I doing wrong?
My models.py:
from django.db import models
from django.contrib.auth.models import User
class Client(User):
address = models.CharField(max_length=255)
state = models.CharField(max_length=255, null=True)
city = models.CharField(max_length=255,null=True)
phone = models.IntegerField()
My forms.py:
from django.contrib.auth.models import User
class Auth(forms.ModelForm):
class Meta:
model = User #I tried here both User and Client and returns the same result (form isn't valid)
fields = [
'username',
'password',
]
labels = {
'username': '',
'password': '',
}
widgets = {
'username': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Usuario', 'style':'margin-bottom:15px'}),
'password': forms.PasswordInput(attrs={'class':'form-control','placeholder':'Contraseña'}),
}
My views.py:
from django.shortcuts import render
from .models import Cart
from .forms import Auth
from django.shortcuts import redirect
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
def main(request):
productos = Cart.objects.all()
users=User.objects.all()
if request.method == 'POST':
if request.user.is_authenticated:
messages.warning(request,'Ya existe un usuario autenticado')
return redirect('main')
else:
form = Auth(request.POST)
if form.is_valid():
user=form['username'].value()
password=form['password'].value()
authuser=authenticate(request,username=user,password=password)
if authuser is not None:
login(request, authuser)
messages.success(request, 'Bienvenido')
return redirect('main')
else:
messages.error(request, 'Credenciales no válidas')
return redirect('main')
else:
form = Auth()
return render(request, 'index.html', {"form": form, 'productos':productos,'users':users})
The authenticate() function returns the right value, so the authuser variable is not None. But I don't know why the login() function does nothing, even when I try to login the user from the admin interface.
First you shouldn't use inherit of the Django base User:
from django.contrib.auth.models import User
If you whant extand the django user classe, use this one:
from django.contrib.auth.models import AbstractUser
Here is the link from the django docs: link
Here is an other link if find useful: link

login authentication in django

I want to use the authenticaton for custom user model in django. i just created the authentication for custom user model. but it's not validating the username and password. anyone help for that where i was mistaken the code.
Here it is my views.py file :
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
def loginpage(request):
if request.method =='POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request,username=username,password=password)
if user is not None:
login(request,user)
return redirect('profile')
else:
return render(request, 'login.html', {})
Your authenticate logic is wrong. Because you gave queryset to authenticate function.You can provide username and password directly. There is a sample for authenticate based on doc
And change your request.POST.['username'] with request.POST.get("username"),
request.POST.['password'] with request.POST.get("password")
from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
if user is not None:
# User exist
else:
# No user founded with this username and password