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():
Related
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.')
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"]
I know there are hundreds of posts about that topic but, in all of them, there is something slightly different from my own program and I can't adapt it to my program because the Django way of handling password is such a mess that I understand nothing. A little help would be greatly appreciated, I thank you in advance.
So, when a new user registers, everything works perfectly but, somehow, the password is not saved in the database. When I go to the admin interface, it tells me that the password format is invalid or the hashag function is not known.
Here is my code :
Forms.py
class InscriptionForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'password']
widgets = {'username': forms.TextInput(attrs={'class': 'form-control'}),
'first_name': forms.TextInput(attrs={'class': 'form-control'}),
'last_name': forms.TextInput(attrs={'class': 'form-control'}),
'email': forms.EmailInput(attrs={'class': 'form-control'}),
'password': forms.PasswordInput(attrs={'class': 'form-control'})}
def clean_password(self):
password = self.cleaned_data['password']
try:
validate_password(password, user=self)
except forms.ValidationError:
self.add_error('password', password_validators_help_texts())
return password
Views.py
def inscription(request):
if request.method == "POST":
form = InscriptionForm(request.POST)
if form.is_valid():
new_user = form.save()
authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'],)
login(request, new_user)
request.session['is_connected'] = True
return redirect(inscription_suite)
else:
form = InscriptionForm()
return render(request, 'inscription/inscription.html', {'form': form})
I already tried modifying the view like this :
def inscription(request):
if request.method == "POST":
form = InscriptionForm(request.POST)
if form.is_valid():
new_user = form.save(commit=False)
new_user.password = make_password(form.cleaned_data['password'])
authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'],)
login(request, new_user)
new_user.save()
request.session['is_connected'] = True
return redirect(inscription_suite)
else:
form = InscriptionForm()
return render(request, 'inscription/inscription.html', {'form': form})
But it raises the following error ValueError at /inscription
Cannot force an update in save() with no primary key.
Can someone help me please ?
Thanks in advance !
You must save password using set_password().
def inscription(request):
if request.method == "POST":
form = InscriptionForm(request.POST)
if form.is_valid():
new_user = form.save(commit=False)
password = form.cleaned_data['password'] # get password
new_user.set_password(password) # set the password
new_user.save() # save the user
authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'],)
login(request, new_user)
request.session['is_connected'] = True
return redirect(inscription_suite)
else:
form = InscriptionForm()
return render(request, 'inscription/inscription.html', {'form': form})
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})
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")