Make it possible to sign up - 30 days of Django

Make it possible to sign up - 30 days of Django

/ #Django


It would be cool to make it possible to separate tasks based on the user. So let's learn about authentication today.

Making it possible for users to sign up is very easy thanks to the built in authentication system in Django. Let's begin with creating a new Django app for users:

$ python manage.py startapp userprofile

And then we need to append it to a list in the "settings.py" file.

INSTALLED_APPS = [
    ...
    'userprofile',
]

Django comes with a built in database model for users, so this app will only be used for views and templates. Open up userprofile/views.py, it should look like this:

from django.contrib.auth import login
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():
            user = form.save()

            login(request, user)

            return redirect('frontpage')
    else:
        form = UserCreationForm()
    
    return render(request, 'userprofile/signup.html', {'form': form})

Most of this code should hopefully start looking familiar and make sense now?
We import a method from Django for logging in the user, and a form for creating the user. If the form is valid, we store the form in a variable called "user", then we log in the user and redirect to the front page.

Next step then is to create the folder for the template (templates/userprofile) and the template inside "signup.html". It should look like this:

{% extends 'task/base.html' %}

{% block content %}
    <div class="edit-tasks">
        <h1>Sign up</h1>

        <form method="post" action=".">
            {% csrf_token %}

            {{ form.as_p }}

            <button>Sign up</button>
        </form>
    </div>
{% endblock %}

So yet again, a very simple template where we render a form.

The last step then is to create a url file and also appending it in the main urls.py file. Create a file called urls.py in the new userprofile app:

from django.urls import path

from . import views

urlpatterns = [
    path('sign-up/', views.signup, name='signup'),
]

And then add it in the main urls.py file:

from django.urls import path, include

urlpatterns = [
    path('', include('userprofile.urls')), # New
    path('', include('task.urls')),
    path('', include('category.urls')),
]

Try to create a user and see what happens. In the next part, we will handle log in and making a few checks if the user is authenticated or not.

Table of contents

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.