Unlike the login and logout pages we built previously in Part 1: Login & Logout, the built-in Django auth app does not supply us with a view for creating a new user. It does however provide us with a form class, UserCreationForm, which we can use to create new users. By default it comes with three fields: username, password1, and password2.

There are many ways to organize your code and url structure for a robust user authentication system. Here we will create a new app register_app for our Signup page.

(users) $ ./manage.py startapp register_app

Add the new app to the INSTALLED_APPS setting in our settings.py file.

# my_project/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'register_app',
]

Next add a project-level view pointing to this new app.

# my_project/urls.py
from django.views.generic.base import TemplateView

urlpatterns = [
    url(r'^$', TemplateView.as_view(template_name='index.html'), name='index'),
    url(r'^admin/', admin.site.urls),
    url(r'^users/', include('django.contrib.auth.urls')),
    url(r'^signup/', include('register_app.urls')),
    url(r'^$', TemplateView.as_view(template_name='index.html'), name='index'),
]

On the next-to-last line we’ve indicated the url pattern will be signup/ and simply pointed it to our app-level urls.

Let’s go ahead and create our register_app/urls.py file. We are simply importing a view called “signup” (which we haven’t made yet), and then indicating the signup page will be at /signup.

# register_app/urls.py
from django.conf.urls import url

from .views import signup


urlpatterns = [
    url(r'^$', signup),
]

Our view is written from scratch, albeit using Django’s UserCreationForm.

# register_app/views.py
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect

def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(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('index')
    else:
        form = UserCreationForm()
    return render(request, 'signup.html', {'form': form})

At the top we import both the login and authenticate modules from the auth app, as well as UserCreationForm. We also add render and redirect which we’ll use to display the page and redirect the user to a new page upon successful registration.

In the view itself signup we specify our method, POST, the form, and then perform basic form validation. Finally upon success we redirect to our homepage via its named url index.

Final step is to create a template for our signup form. We’ll add this within our existing templates folder.

<!-- templates/signup.html -->
{% extends 'base.html' %}

{% block content %}
  <h2>Sign up</h2>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Sign up</button>
  </form>
{% endblock %}

This format is very similar to what we’ve done before. We use the csrf_token for security, display the forms contents in paragraph tags with form.as_p, and add a submit button.

We’re now done! To test it out, navigate to our newly created page http://127.0.0.1:8000/signup/.

Django signup page

Upon submission you will be redirected to the homepage and greeted with a personalized “Hi !" greeting.

Homepage for user wsvincent

Next Steps

So far we’ve only implemented the very basics of user authentication. Django provides the ability to segment users by permission level and groups. I recommend opening the Django admin and exploring some of the additional functionality available with our newly created users.

Next up we’ll learn how to create a reset password form. Stay tuned!




If you’d like to learn more about Django and build step-by-step multiple web applications, check out the free online book I wrote Django For Beginners.