Require Email When Creating an Account with Django - python

I've got a Django project, which requires users to be able create accounts to access content.
I'm using the UserCreationForm to do this.
In views.py I have
def register_user(request):
if request.method == "POST":
user_form = UserCreationForm(request.POST)
if user_form.is_valid():
new_user = user_form.save(commit=False)
new_user.set_password(user_form.cleaned_data["password1"])
new_user.save()
template = "account/registration/registration_done.html"
context = {"new_user": new_user}
else:
# TODO: Handle exception
raise BaseException
elif request.method == "GET":
user_form = UserCreationForm()
template = "account/registration/register.html"
context = {"user_form": user_form}
else:
raise NotImplementedError
return render(request, template, context=context)
And then my template is:
{% extends "base.html" %}
{% block title %}Create an Account{% endblock %}
{% block content %}
<h1>Create an Account</h1>
<form action="." method="post">
{{ user_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Create my account"></p>
</form>
{% endblock %}
Which works okay. But when the create account form is displayed, it only has fields for the username, password, and password verification. There's no requirement that the user enter a valid email.
What I'd like to do is have a have the user be required to enter an email address, and then send them an email to ensure that the address is valid, and that they have access to is etc.
Surely this is a common enough pattern that there's already a way to implement is using Django's authentication? Or will I need to write all the forms and handling etc myself?

Override the Meta class of the UserCreationForm
In your forms.py
from django.contrib.auth.forms import UserCreationForm
class YourUserCreationForm(UserCreationForm)
class Meta:
fields = ("username", "email")
and use YourUserCreationForm instead

Related

The form validation returning False in Django

views.py
def student_login(request):
form = StudentLoginForm()
if request.method == 'POST':
form = StudentLoginForm(data=request.POST)
print(form.is_valid())
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
print(username)
user = authenticate(username=username,password=password)
if user is not None:
login(request,user)
return redirect('index')
else:
messages.error(request,'Invalid username or password!')
else:
messages.error(request,'Invalid username or password!')
context = {'form':form}
return render(request,'student_login.html',context)
models.py
class Student(models.Model):
name = models.CharField(max_length=100)
username = models.CharField(max_length=100,unique=True,default=None)
mobile = models.CharField(max_length=8)
email = models.CharField(max_length=200,unique=True)
password = models.CharField(max_length=200,default=None,unique=True)
total_books_due = models.IntegerField(default=0)
def __str__(self):
return self.name
forms.py
class StudentLoginForm(forms.ModelForm):
class Meta:
model = Student
fields = ['username','password']
widgets = {
'password':forms.PasswordInput(),
}
student_login.html
{% extends 'base.html' %}
<!-- {% load crispy_forms_tags %} -->
{% block content %}
<div class="container">
<br>
<h2>Student Login Form</h2>
<br>
<form method="POST" action="">
{% csrf_token %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-danger" role="alert">
{{ message }}
</div>
{% endfor %}
{% endif %} <br>
{% for field in form %}
<p>{{ field.label }} </p>
<p>{{ field }} </p>
<br>
{% endfor %}
<br>
<input type="submit" class="btn btn-primary" value="Login">
</form>
</div>
{% endblock %}
I have been trying to change again and again but form.is_valid() is still returning False. I could not figure out the reason that the form is not valid because I have already specify the fields that I want to show and added the csrf_token. Could anyone help me to figure out where is the problem?
Try to use just a simple form and not a ModelForm, as ModelForms in the background work with creating and updating objects.
In this case, ModelForm is validating as if you are trying to create a new Student, causing the already exists failures.
For example, you can write a simple login form like this:
class StudentLoginForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(attrs={'autofocus': True}))
password = forms.CharField(
label='Password',
strip=False,
widget=forms.PasswordInput,
)
And then in your views, use it as is:
def student_login(request):
form = StudentLoginForm()
if request.method == 'POST':
form = StudentLoginForm(data=request.POST)
if form.is_valid():
user = authenticate(
username=form.cleaned_data.get('username'),
password=form.cleaned_data.get('password'),
)
if user:
login(request, user)
return redirect('index')
messages.error(request, 'Invalid username or password!')
context = {'form':form}
return render(request,'student_login.html',context)
can you please change this line
form = StudentLoginForm(data=request.POST)
to
form = StudentLoginForm(request.POST)
and also why you are validating the fields as you already validating using .is_valid()
function?
Just create a simple form with username and password. Also, the password field should not be unique if you are using plain text.
Better to use inbuilt User model provided by django. If you want to extend fields in User model, use AbstractUser and override the User model. See in documentation https://docs.djangoproject.com/en/3.2/topics/auth/customizing/

django user creation form with auth.user clean method

I have created a form to add users in my front-end but the form does not validate duplicated username.I am using auth.user model.
This is my code:
views.py
from django.contrib.auth.models import User, Group
#login_required(login_url='/login/')
#permission_required('auth.add_user',raise_exception=True)
def user_new(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.set_password(user.password)
user.save()
return redirect('userdetail', user.id)
else:
form = NewUserForm()
return render(request, 'ace/user_edit.html', {'form': form})
forms.py
class NewUserForm(forms.ModelForm):
class Meta:
model = User
fields = ['username','first_name','last_name','password','email','is_active','is_staff','groups']
widgets = {
'username':TextInput(attrs={'class': u'form-control'}),
'first_name':TextInput(attrs={'class': u'form-control'}),
'last_name':TextInput(attrs={'class': u'form-control'}),
'password':PasswordInput(attrs={'class': u'form-control'}),
'email':EmailInput(attrs={'class': u'form-control'}),
'is_active':NullBooleanSelect(attrs={'class': u'form-control'}),
'is_staff':NullBooleanSelect(attrs={'class': u'form-control'}),
'groups':SelectMultiple(attrs={'class': u'form-control'}),
}
def clean_username(self):
username = self.cleaned_data['username']
user_exists = User.objects.get(username=username)
if user_exists:
raise ValidationError("User exists")
template
...
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
<form method="POST" class="service-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-info">Salvar</button>
<a href="{% url 'userlist' %}">
<button class="btn btn-danger" type="button">Cancelar</button>
</a>
</form>
...
When I create a new user OK, but when a try create a user that same username of other I get a error:
The view ace.views.user_new didn't return an HttpResponse object. It
returned None instead.
If I add a print line "print form.errors" in view i get in console:
usernameUser
exists
Your view does not have an else statement for if, form is not valid it should render the template with form errors.
You need to change your view like this,
def user_new(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.set_password(user.password)
user.save()
return redirect('userdetail', user.id)
else:
return render(request, 'ace/user_edit.html', {'form': form})
else:
form = NewUserForm()
return render(request, 'ace/user_edit.html', {'form': form})
And also you need to add the tag {%for field in form%} {{field.error}}{%endfor%} along with the form fields and labels.
You need to make sure that your view returns a response for POST requests when the form is invalid. You can do this by moving the final return render() statement out of the else block.
def user_new(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
...
return redirect('userdetail', user.id)
else:
form = NewUserForm()
return render(request, 'ace/user_edit.html', {'form': form})
For registration django.contrib.auth User needs the username field to be unique. If you want to use other model field as unique (as unique registration field) and not the username, for example the email field, you can use this approach or use other registration bakends like django registration or django registration redux.
Instead of fixing the bug in your code I suggest to not invent the wheel and use excellent django-allauth package. It handles user login, logout, change password, registration and social sign in. I always start new projects from adding django-allauth - it handles all authentication problems with no effort.
You can use the saved time and effort to write actual application code instead of solving trivial user management details.
Also, the proper way to check for existence of the model instance is this:
user_exists = User.objects.filter(username=username).exists()
if user_exists:
raise ValidationError("User exists")

Django only login for shell created users

I let a user sign up due to the following code:
def sign_up(request):
if request.POST:
userName = request.POST.get('username')
passWord = request.POST.get('password')
user = User.objects.create_user(username=userName, password=passWord)
user.save()
return HttpResponseRedirect(reverse('account:login'))
args = {}
args.update(csrf(request))
args['form'] = UserCreationForm()
return render_to_response('account/sign_up.html', args, context_instance=RequestContext(request))
TEMPLATE:
{% extends "base_login.html" %}
{% load staticfiles %}
<div id="sign_up"> {% block extension1 %}
<form action="/account/sign_up/" method="post"> {% csrf_token %}
{{ form }} <br/>
<input type="submit" value="Sign up"/>
</form> {% endblock %}
</div>
The user gets created. I can see this in the database. However, following this way, this newly created user wouldn't be albe to login. Though, users created the same way in shell will be able to login. I tried a lot and found:
users_able.password
'pbkdf2_sha256$12000$CczM6MmFkTrj$qA1QG7O4nBSSOh6...'
users_unable.password
'!KAXKN25DPijEmzj0TcrhpHYpyB1pLhue...'
So I suppose it has something to do with the password not set properly. Right? I use the default UserCreationForm for signing up. Any ideas?
Referring to How to use django UserCreationForm correctly:
You can directly save the UserCreationForm which will give you user object.
Allowing you to do something like this:
def sign_up(request):
if request.POST:
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
return HttpResponseRedirect(reverse('account:login'))
...
Django's UserCreationForm doesn't have a field named password. It has a named password1 and has a password2 field that when enetered should match password1. If you change request.POST.get('password') to request.POST.get('password1') I'm sure this would work. However, I would recommend you not use your method as it's built. You should be seeing if the form is valid before creating a user.

validating email in registration is not raising validationError in Django?

In my registration, I am enforcing that email-id is unique. That is if a user exists with that email-id, I want to raise a forms.ValidationError.
Here is my form.py:
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class MyRegistrationForm(UserCreationForm):
#define fields
email=forms.EmailField(required=True)
class Meta:
model=User
fields=('username','email','password1','password2')
def clean_email(self):
email = self.cleaned_data["email"]
try:
user = User.objects.get(email=email)
print user.email
print user.username
raise forms.ValidationError("This email address already exists. Did you forget your password?")
except User.DoesNotExist:
return email
def save(self, commit=True):
user = super(MyRegistrationForm, self).save(commit=False)
user.email=self.cleaned_data["email"]
if commit:
user.save()
return user
my view.py:
def register_user(request):
if request.method=='POST':
form=MyRegistrationForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, "Thank you for signing up")
return HttpResponseRedirect("/accounts/register_success")
args={}
args['form']=MyRegistrationForm()
return render(request,"register.html",args)
when I register a user with same email id, it does not throw validationError. but simply return the register.html but no duplicate user is added.
why is it not throwing validationError?
I added a couple of print statements in forms.py (above) to print the username and email that I get from User.object.get(email=email) and it correctly prints the name and email id of previously registered user. so the control proceeds till there but it is not throwing validationError
EDIT:
I also tried creating a brand new user, but having passoword fields Not match.
still, I do not get any error message. but it simply redirects to register.html
EDIT:
template/register.html
{% extends "base.html" %}
{% block content %}
<h2>Register</h2>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="register"/>
</form>
{% endblock %}
In this template, error gets displayed automatically right above the field where the error occurs. I don't have to do {{ form.email.error }}. However, I do not have a way to customize the error. eg bold or some css to them. Is that possible?
Django forms catch ValidationError exception and adds error to form _errors dict. This code from django BaseForm._clean_fields method:
try:
# ...
if hasattr(self, 'clean_%s' % name):
value = getattr(self, 'clean_%s' % name)()
self.cleaned_data[name] = value
except ValidationError as e:
self._errors[name] = self.error_class(e.messages)
if name in self.cleaned_data:
del self.cleaned_data[name]
So, by raising ValidationError exception you are telling django to add errors to cleaning field and make your form not valid.
You can access field error in template:
{{ form.field_name.errors }}
and iterate one field errors (django docs Customizing the form template):
{% if form.subject.errors %}
<ol>
{% for error in form.subject.errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
</ol>
{% endif %}
and all fields errors (django docs Looping over the form’s fields):
{% for field in form %}
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% endfor %}
and display non field errors:
{{ form.non_field_errors }}
update: you should add else block in view. Without else you are always create new form:
def register_user(request):
if request.method=='POST':
form=MyRegistrationForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, "Thank you for signing up")
return HttpResponseRedirect("/accounts/register_success")
else:
form = MyRegistrationForm()
args={}
args['form'] = form
return render(request,"register.html",args)

Django method to change User email not working

I am attempting to create a page where a user can see what their current email is and change it if they would like. I am just testing with a very simple form and a very simple HttpResponseRedirect if the form is not valid. However neither my email is changing for the user nor is my failure response if the form is not valid working. I am not sure what is causing this
forms.py:
class ChangeEmail(forms.Form):
email1 = forms.EmailField(label=u'Type new Email')
email2 = forms.EmailField(label=u'Type Email again')
views.py:
def change_email(request, username):
if request.method == 'POST':
user1 = User.objects.get(username=username)
form1 = ChangeEmail(request.POST)
if form1.is_valid():
user1.email = form.cleaned_data['email1']
form1.save()
return HttpResponseRedirect('/register/success')
else:
return HttpResponseRedirect('/stupid')
else:
user = User.objects.get(username=username)
email = user.email
form = ChangeEmail()
variables = RequestContext(request, {
'form': form,
'email': email
})
return render_to_response('registration/email.html', variables
Thanks for your help in advance.
EDIT:
The URL that I have mapped to render the form is /user/testuser/email. I am attempting to put in invalid input in to the fields to get an error message but when I push submit it redirects me back to /user/testuser page which displays info about the user. My change email template is below:
{% extends "base.html" %}
{% block title %}Change Email{% endblock %}
{% block head %}Change Email{% endblock %}
{% block content %}
<p> Current Email: {{ email }} </p>
<form method="post" action=".">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Change Email" />
</form>
{% endblock %}
ChangeEmail is a normal form. These don't have save methods - only ModelForms do. You're correctly setting the user email from the form's cleaned_data - but you should be saving the user1 object, not the form.
Also, it's best not to redirect away on validation failure. Leave out that first else clause, and move the variables/render_to_response lines back one indentation level, and the form will be redisplayed with any errors.
views.py:
def change_email(request, username):
# a common django idiom for forms
form1 = ChangeEmail(request.POST or None)
user1 = User.objects.get(username=username)
if form1.is_valid():
#check that emails are the same
if form.cleaned_data['email1'] == form.cleaned_data['email2']:
user1.email = form.cleaned_data['email1']
#Save the user object here, since we're not dealing with a ModelForm
user1.save()
return HttpResponseRedirect('/register/success')
# We're presenting them with the empty form if something went wrong
# and redisplaying. The form's field errors should be printed out in
# the template
else:
user = User.objects.get(username=username)
email = user.email
variables = RequestContext(request, {
'form': form,
'email': email
})
return render_to_response('registration/email.html', variables)

Categories