Boone Putney bio photo

Boone Putney

Software Development
Random Musings
Austin, Texas

HumanPlanet Soleer

Email LinkedIn Github

I’m a huge believer in simple interfaces, and not overwhelming users with form fields. While not always the best option, for most of our projects, it’s much cleaner to have a user register with just an email and a password.

Here is our quick and dirty implementation for extending the user form from the django.contrib.auth module to work for our use case.

Form

We want to extend the base UserCreationForm found in django.contrib.auth.forms. To do so, we need to:

  1. Extend the UserCreationForm class.
  2. Add in the email field.
  3. Specify the form fields.
  4. Pop (remove) the username field on init.
  5. Alter the save function so the email is added to the user record, and the email is recorded to the username field

forms.py:

 1 from django import forms
 2 from django.contrib.auth.models import User
 3 from django.contrib.auth.forms import UserCreationForm
 4 
 5 
 6 class UserRegisterForm(UserCreationForm):
 7     email = forms.EmailField(required=True)
 8 
 9     class Meta:
10         model = User
11         fields = ("email", "password1", "password2")
12 
13     def __init__(self, *args, **kwargs):
14         super(UserRegisterForm, self).__init__(*args, **kwargs)
15         # remove username
16         self.fields.pop('username')
17 
18     def save(self, commit=True):
19         user = super(UserRegisterForm, self).save(commit=False)
20         user.email = self.cleaned_data["email"]
21         # write email to username
22         user.username = user.email
23         if commit:
24             user.save()
25         return user

View

In the view.py file, we need to check the post for valid data, using our new form. If the submitted data is valid, we save the user and redirect to the homepage. Otherwise, return to the registration page:

views.py:

 1 def register(request):
 2     if request.method == 'POST':
 3         form = UserRegisterForm(request.POST)
 4         if form.is_valid():
 5             form.save()
 6             return HttpResponseRedirect("/")
 7     else:
 8         form = UserRegisterForm()
 9     return render(request, "registration/register.html", {
10         'form': form,
11     })

Template

register.html:

1 <form action="{% url 'register' %}" method="post" class="form-register" >
2     <h1>Create an account</h1>
3     {% csrf_token %}
4     {{ form.as_p }}
5     <input type="submit" value="Create the account">
6 </form>

Closing remarks

As we stated earlier, this is a quick and dirty implementation, but it should give you a starting point. You will also need to handle special characters that are illegal for username usage, and username length restrictions, among other things.