Django forms is_valid() for registration, always false - python

I'm still learning django and I'm trying to create a register and login page.
I beleive i created the form right, and the .is_valid() looks good to me also, I have no idea what i did wrong.
every time I submit the register form, it fails and renders the else condition, same with the login function, even thought I went into admin to add a user manually.
my user model is called 'Users'
Forms:
class reg_form(forms.Form):
username = forms.CharField(label='username', max_length=64)
password = forms.CharField(widget=forms.PasswordInput)
email = forms.EmailField(label="email", max_length=64)
phone = forms.CharField(label='Phone', max_length=64)
first_name = forms.CharField(label='First Name', max_length=64)
last_name = forms.CharField(label='Last Name', max_length=64)
class log_form(forms.Form):
username = forms.CharField(label='username', max_length=64)
password = forms.CharField(widget=forms.PasswordInput)
Register:
def register(request):
if request.method == 'POST':
form = reg_form(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
email = form.cleaned_data['email']
phone = form.cleaned_data['phone']
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
user = Users.objects.Create(username=username, email=email, password=password, phone=phone, first_name=first_name, last_name=last_name)
Users.save(user)
login(request, user)
return render(request, 'profile.html')
else:
return render(request, 'register.html', {
'form': reg_form
})
else:
return render(request, 'register.html', {
'form': reg_form
})
login:
def log_in(request):
if request.method == 'POST':
form = log_form(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return render(request, 'profile.html')
else:
return render(request, 'login.html', {
'form2': log_form
})
else:
return render(request, 'login.html', {
'form2': log_form
})
else:
return render(request, 'login.html', {
'form2': log_form
})

To see the errors you should return Bound Form:
def register(request):
if request.method == 'POST':
form = reg_form(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
email = form.cleaned_data.get'email')
phone = form.cleaned_data.get('phone')
first_name = form.cleaned_data.get('first_name')
last_name = form.cleaned_data.get('last_name')
user = Users.objects.create(
username=username, email=email,
password=password, phone=phone,
first_name=first_name, last_name=last_name
)
login(request, user)
return render(request, 'profile.html')
else:
return render(request, 'register.html', {
# If the form not valid return bound form
'form': form
})
else:
return render(request, 'register.html', {
'form': reg_form
})
And do the same in your log_in view.
I suggest you to use ModelForm.
Also see Coding style (Django Docs):
Use InitialCaps for class names (or for factory functions that return
classes).
Field names should be all lowercase, using underscores instead of
camelCase.

Related

Populate Django username field with generated username

I would like the user name field for my Django registration to populate with the following function -
def generateUsername():
username = firstname[0] + middlename[0] + lastname[0] + randomStringDigits(6) + getDateTimeStr()
return username
I am currently using the UserRegisterForm model from Django and would prefer to find away to integrate into this, however if the best option is to custom my own user model then I am happy to do this also.
views.py -
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
forms.py -
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
firstname = forms.CharField(max_length=20)
middlename = forms.CharField(max_length=20)
lastname = forms.CharField(max_length=20)
class Meta:
model = User
fields = ['email', 'firstname', 'middlename', 'lastname']
You can set this to the user object wrapped in the form:
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
data = form.cleaned_data
username = f"{data['firstname'][0]}{data['middlename'][0]}{data['lastname'][0]}{randomStringDigits(6)}"
form.instance.username = username
form.save()
messages.success(request, f'Account created for {username}')
return redirect('login')

Understanding the def clean(self) method inside custom login form class

Django Version = 2.2.2.
Does it not make sense to take out the def clean(self) method from class LoginForm(form.ModelForm)
class LoginForm(forms.ModelForm):
password = forms.CharField(label='Password', widget=forms.PasswordInput)
class Meta:
model = Account
fields = ['email', 'password']
def clean(self):
if self.is_valid():
email = self.cleaned_data['email']
password = self.cleaned_data['password']
if not authenticate(email=email, password=password):
raise forms.ValidationError('Invalid login')
and put it inside the view function for login:
def login_screen_view(request):
context = {}
if request.POST:
form = LoginForm(request.POST)
if form.is_valid():
email = request.POST['email']
password = request.POST['password']
user = authenticate(email=email, password=password)
if user:
login(request, user)
return redirect('home')
else:
form = LoginForm()
context['login_form'] = form
return render(request, 'account/login.html', context)
So that the above two blocks of code becomes now this:
class LoginForm(forms.ModelForm):
password = forms.CharField(label='Password', widget=forms.PasswordInput)
class Meta:
model = Account
fields = ['email', 'password']
def login_screen_view(request):
context = {}
if request.POST:
form = LoginForm(request.POST)
if form.is_valid():
email = request.POST['email']
password = request.POST['password']
user = authenticate(email=email, password=password)
if user:
login(request, user)
return redirect('home')
else:
raise forms.ValidationError('Invalid login') #i added this line
else:
form = LoginForm()
context['login_form'] = form
return render(request, 'account/login.html', context)
The reason why I say all this is because in the def clean(self) method aren't you basically checking if the form is valid? We also check if the form is valid in the view as well. So why repeat the logic? Then if we cannot authenticate the user we raise a ValidationError which I think can be added in the view definition.

I want to make sign in & up for my site with Django but it doesn't work

form.py
class SignUpForm(forms.Form):
name = forms.CharField(max_length=50, required=True)
email = forms.EmailField(max_length=100, required=True)
password = forms.CharField(max_length=20, required=True)
class SignInForm(forms.Form):
email = forms.EmailField()
password = forms.CharField(max_length=20, min_length=8)
view.py
def Sign_Up(request.POST):
if request.method == 'POST':
form = SignUpForm(request)
if form.is_valid():
cd = form.cleaned_data
name = cd['name']
email = cd['email']
password = cd['password']
us = User..objects.get(email__exact=email, password__exact=password)
return HttpResponseRedirect('/')
else:
form = SignUpForm()
return render(request,'User Login Page.html', {'form':form})
def Sign_In(request.POST):
if request.method =='POST' :
form = SignInForm(request)
if form.is_valid():
F = form.cleaned_data
Eemail = F['email']
Epassword = F['password']
try:
user = User.objects.filter(email=Eemail)
except User.DoesNotExist:
form = SignInForm()
return render(request, "Admin Login Page.html", {'form': form})
if User.password == Epassword:
return HttpResponseRedirect("/")
form = SignInForm()
return render(request,"Admin Login Page.html",{'form':form})
I want to make a sign in & up for my site with Django but it doesn't work!
When I click on the submit button my sign up directly goes to the HttpRsponseDirect address even with empty parameters
def Sign_Up(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
name = cd['name']
email = cd['email']
password = cd['password']
user = form.save()
user.refresh_from_db()
user.save()
user = authenticate(username=email, password=password)
return HttpResponseRedirect('/')
else:
form = SignUpForm()
return render(request,'signup.html', {'form':form})
def Sign_In(request):
if request.method =='POST' :
form = SignInForm(request)
if form.is_valid():
F = form.cleaned_data
Eemail = F['email']
Epassword = F['password']
user=authenticate(username=F,password=Epassword)
if user is not None:
return HttpResponseRedirect("/")
else:
form=SignInForm()
message='login failed'
retuen render(request,'login.html',{'form':form,'message':message})
look at upside code
Unless you have multiple security experts on the job; please, please, please let someone else handle your logins like Google or Facebook. like when you go to create account it says "use google to sign in"

Django User Creation

I am doing a basic user creation using the built-in UserCreationForm in Django.
Here is my views.py:
def user_register(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
raw_password = form.cleaned_data['password1']
user = User.objects.create_user(username=username)
if raw_password:
user.set_password(raw_password)
else:
user.set_unusable_password()
user.save()
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form': form})
However, after registering a user and being redirected to home, the number of Users seen in my Admin page has not changed; no User has been created.
Any idea what I am doing wrong here?
Try:
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
def user_register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user=User.objects.create_user(username=username, password=password)
user.save()
#Below 2 lines, if you want user to get logged in
user = authenticate(username=username, password=password)
login(request, user)
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form': form})
don't know why you can redirected to home with no use create,but you should deal with the situation form is not vaild and remove form.save() from form.is_valid() block like:
form = UserCreationForm(request.POST)
if form.is_valid():
# remove form.save()
....
else:
print(form.errors.as_text())
return render(request, 'registration/register.html', {'form': form})
or override save method for UserCreationForm like i do:
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
the full demo is:
from django.views.generic import *
class RegisterView(FormView):
template_name = 'registration/register.html'
form_class = UserCreationForm
success_url = reverse_lazy('home')
def form_valid(self, form):
form.save()
return HttpResponseRedirect(self.get_success_url())
forms.py
class UserCreationForm(forms.ModelForm):
error_messages = {
'duplicate_username': u"duplicate username",
'password_mismatch': u"password_mismatch",
'duplicate_email': u'duplicate email'
}
username = forms.RegexField(
max_length=30,
regex=r'^[\w.#+-]+$',
error_messages={
'invalid': u"onlay can contaions symbol #/./+/-/_",
'required': u"required"
},
label='username'
)
email = forms.EmailField(
error_messages={
'invalid': u"email invalid",
'required': u'required'},
label='email'
)
password1 = forms.CharField(
widget=forms.PasswordInput,
error_messages={
'required': u"required"
},
label='password1 '
)
password2 = forms.CharField(
widget=forms.PasswordInput,
error_messages={
'required': u"required"
},
label='password2'
)
def __init__(self, *args, **kwargs):
super(UserCreationForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs.update({'class': 'form-control'})
self.fields['email'].widget.attrs.update({'class': 'form-control'})
self.fields['password1'].widget.attrs.update({'class': 'form-control'})
self.fields['password2'].widget.attrs.update({'class': 'form-control'})
class Meta:
model = User
fields = ("username", "email")
def clean_username(self):
# Since User.username is unique, this check is redundant,
# but it sets a nicer error message than the ORM. See #13147.
username = self.cleaned_data["username"]
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(
self.error_messages["duplicate_username"]
)
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages["password_mismatch"]
)
password_validation.validate_password(password2)
return password2
def clean_email(self):
email = self.cleaned_data["email"]
try:
User.objects.get(email=email)
except User.DoesNotExist:
return email
raise forms.ValidationError(
self.error_messages["duplicate_email"]
)
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
I don't know why you are saving the object so many times. As documented here, when calling form.save() in a UserCreationForm instance, Django will create the user, set the password (which comes from the password1 field), save the instance in the database and return the user for you. So User.objects.create_user and user.save() will only save the object again.
Parhaps it's not the solution for your problem but have you tried just like this:
def user_register(request):
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
# if you want to authenticate your user or log any info, do it here
return redirect('home')
# I wouldn't use the else statement here, so if there are errors in the form you probably want the same template to be rendered, in order to show the form errors to your user.
return render(request, 'registration/register.html', {'form': form})
Thanks for everybody that helped me think this through. It seems, of course, the answer was much simpler than I thought. My new user_register view is:
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
def user_register(request):
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
return render(request, 'registration/register.html', {'form': form})

Check user submitted password in database

I'm new in Django programming and I'm stuck in this problem.
This is the code that I have in views.py:
def login(request):
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
else:
context = RequestContext(request, {})
return render(request, 'login.html', context)
How can I search the user that have the email inserted in the html form, and check if the password is correct?
Thanks in advance for your help.
Try this:
def login(request):
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
# Assuming the fields in your `User` model are labeled the same
user = authenticate(email=email, password=password)
else:
context = RequestContext(request, {})
return render(request, 'login.html', context)

Categories

Resources