Email Verification in Django when a new user signs up - django

I am creating a user registration page for my website. I want to send an email verification mail to the mail the user inputs while registering. I tried many solutions but nothing seems to work for me.
My code:
views.py
def registerPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST, request.FILES)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
messages.success(request, 'Account was created for ' + username)
return redirect('login')
context = {'form': form}
return render(request, 'Home/register.html', context)
def loginPage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.info(request, 'Username OR password is incorrect')
return redirect('login')
context = {}
return render(request, 'Home/login.html', context)
forms.py
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ["username", "email", "password1", "password2"]

Related

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():

Django Login Authentication: I am able to SignUp new user and create new user as well but UNABLE to login as SignUp user

I'm able to SignUp new user as well but UNABLE to login for handlelogin
def handlelogin(request):
if request.method == 'POST':
loginemail= request.POST['loginemail']
loginpass = request.POST['loginpass']
user = authenticate(request, username=loginemail, password=loginpass)
if user is not None:
print(loginemail, loginpass)
login(request, user)
messages.success(request, "Successfullly Logged-In")
return redirect('/')
else:
messages.error(request, "Invalid Credentials, Please Try Again")
return redirect('/')
return HttpResponse('404 - Page Not Find')
I have tried print() statement to check and it do work in else statement only, not in if user is not none.
NOTE: THE SYNTAX IN QUESTION IS LITTLE BIT DISTURBED... BUT IN CODE IT IS COMPLTELY FINE.
BTW I use Django forms for login and logout users:
views.py:
def user_login(request):
if request.method == 'POST':
form = UserLoginForm(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)
messages.success(request, 'you logged in successfully', 'success')
return HttpResponseRedirect('dashboard/')
else:
messages.error(request, 'username or password is wrong', 'danger')
else:
form = UserLoginForm()
return render(request, 'login.html', {'form': form})
def user_logout(request):
logout(request)
messages.success(request, 'you logged out successfully', 'success')
return HttpResponseRedirect('')
forms.py
class UserLoginForm(forms.Form):
username = forms.CharField(max_length=30)
password = forms.CharField(max_length=50)
urls.py
urlpatterns = [
path('', user_login),
path('logout/', user_logout, name='user_logout'),
]
Also if you haven't make sign Up page you should make user manually by python3 manage.py createsuperuser command.
For sign Up page:
urls.py
urlpatterns = [
...
path('signup/', signup, name='signup'),
]
views.py
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
forms.py
class SignUpForm(UserCreationForm):
first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')

want to remove error message in custom login form in django custom login

i don't want user have to see this message without any error i load page this come automatically here is my views.py
def my_login(request):
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('accounts:home')
else:
return HttpResponse('<h1>Page was found</h1>')
else:
return render(request, "login.html", {'form': form})
my forms.py
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
def clean(self, *args, **kwargs):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
if username and password:
user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError("User does not exist.")
if not user.is_active:
raise forms.ValidationError("User is no longer active.")
return super(LoginForm, self).clean(*args, **kwargs)
You need to submit your form only when you receive a POST request.
def my_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
# process form here
else:
form = LoginForm()
# send form to template
You will find more info about this in the documentation.

Django users can't login after I create an account but admin can

I register a user succesfully. But then when I try to login it says username or password is wrong. This only happens for normal users. Superadmin can login without any problem.
login view
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, 'Logged in succesfully')
return redirect('dashboard')
else:
messages.error(request, 'Username or password is wrong')
return redirect('login')
return render(request, 'accounts/login.html')
register view
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
phone = form.cleaned_data['phone']
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = Account.objects.create_user(
first_name=first_name,
last_name=last_name,
username=username,
email=email,
password=password
)
user.phone = phone
user.save()
messages.success(request, 'Created an account succesfully!')
return redirect('dashboard')
else:
form = RegistrationForm()
context = {
'form': form
}
return render(request, 'accounts/register.html', context)
If you want me to send any other code please specify so I edit the question

Login not working in Django

I'm trying to login but Django is not allowing the navigation to the profile.html
This is what I have so far
views.py
def login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
userObj = form.cleaned_data
print(userObj)
username = userObj['username']
password = userObj['password']
user = authenticate(username=username, password=password)
if user is not None:
print("in login")
login(request)
return render(request, 'profiles.html', {'form': form})
else:
return render(request, 'login_form.html', {'form': form})
else:
return render(request, 'login_form.html')
forms.py
class UserLoginForm(forms.Form):
username = forms.CharField(
required=True,
label='Username',
max_length=32
)
password = forms.CharField(
required=True,
label='Password',
max_length=32,
widget=forms.PasswordInput()
)
Check This Code I have done login Register
https://github.com/gowthamand/django-1.11.5-crud-ajax-login-register
I used Inbuilt Login
I think that you need to pass the user to login function
from django.contrib.auth import authenticate, login as f_login
def login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
userObj = form.cleaned_data
print(userObj)
username = userObj['username']
password = userObj['password']
user = authenticate(username=username, password=password)
if user is not None:
print("in login")
f_login(request, user)
return render(request, 'profiles.html', {'form': form})
else:
return render(request, 'login_form.html', {'form': form})
else:
return render(request, 'login_form.html', {'form': form})