Skip to content

Signup

In this video, we are going to create signup feature in django. Using this feature, user will be able to create a new account and login into the system.

Resources:

Form

At first, we need to create a form in order to perform signup. So, create forms.py file in the user app.

Now, import the UserCreationForm from django.contrib.auth

from django.contrib.auth.forms import (UserCreationForm)

Basically, django provies UserCreationForm which has all the functionality to perform signup. We will inherit this form and use it based on our requirements.

After that, we have to import get_user_model.

from django.contrib.auth import get_user_model


User = get_user_model()

Since, we have created a custom user model, so its better to use this method in order to get the current user model which you have defined.

Now, create a class named SignupForm and inherit this UserCreationForm.

class SignupForm(UserCreationForm):

After that, we have to add a class named "form-control" to every field of this form.

    def __init__(self, *args, **kwargs):
        super(SignupForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs["class"] = "form-control"

Now, we will define the fields that is needed to be included in the signup form.

    class Meta:
        model = User
        fields = [
            "email",
            "first_name",
            "middle_name",
            "last_name",
            "date_of_birth",
            "gender",
            "photo",
            "identity_document_type",
            "identity_document_number",
        ]

In this way, we have created a signup form for our custom user model by inheriting the UserCreationForm.

View

Now, lets try to create a signup view that actually handles the process of creating a new user account.

In the views.py file, at first import the SignupForm and other required methods.

from django.shortcuts import render
from user.forms import SignupForm
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.urls import reverse

Now, create a view named signup.

def signup(request):

Now, we need to handle two things in this view i.e. GET request and POST request.

[At first explain the GET Request and then POST request.]

    # When the user sends a post request
    if request.method == "POST":
        # At first we need to instantiate the form
        form = SignupForm(request.POST, request.FILES)
        # Since, we are also accepting profile image, we need to write request.POST as well as request.FILES
        # Now check whether the form is valid or not ?
        if form.is_valid():
            # Save the form
            form.save()
            # Write a success message for Account Creation
            messages.success(request,"Account Created Successfully ! Please enter the email and password to login")
            return HttpResponseRedirect(reverse("index"))
        # If the form is invalid, write the error message for invalid data.
        messages.error(request, "Please Enter Valid Data")
        # Now, render the same template along with the instantiated form.
        return render(request, "user/signup.html", {"form": form})
    # When the user sends a get request, we need to show the signup form.
    # So create a context having signup form.
    context = {"form": SignupForm()}
    # Then render the signup.html template along with the context.
    return render(request, "user/signup.html", context)

Templates

Since, we have not created the signup.html template so we need to create this.

[Location is user/templates/user/signup.html]

I have attached signup.html file in the resources section. Download it and paste it in this html file.

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

{% block title %} 
    <title>Signup</title>
{% endblock title %}

{% block content %}
<div class="card p-3">
 <div class="card-body">
    <h4>Fill the following details to create a new account</h4>
    {% include "components/auth-form.html" with form_name="Signup" %}
 </div>
</div>
{% endblock content %}

In this html code, I have used a different component named auth-form.html. So, create this file in the auth-form.html.

I have also attached auth-form.html file in the resources section. Download it and paste it in this html file.

In this form, we are writing enctype to multipart/form-data. We need to write this code whenever we are handling any file in the form. In the signup form, there a field for profile image. So, whenever user uploads the image, we need to specify multipart/form-data for the server otherwise django will not be able to get this file.

[auth-form.html]

<form method="POST" action="" enctype="multipart/form-data">
  {% csrf_token %} 

  {% for field in form %}
  <div class="mb-2 row">

    <div class="col-sm-2">
      {{ field.label_tag }}
    </div>

    <div class="col-sm-10 col-md-8 col-lg-6">
      {{ field }}
    </div>

    {% if field.help_text %}
      <span class="help offset-md-2">{{ field.help_text|safe }}</span>
    {% endif %} 

    {% if form.errors %}
      <span class="offset-md-2">{{ field.errors }}</span>
    {% endif %}
  </div>
  {% endfor %}

  <button type="submit" class="btn btn-primary">{{ form_name }}</button>
</form>

URLS

Now, let us write the urls for the view which we have created.

Create a urls.py file in the user app.

from django.urls import path
from user import views

app_name = "user"

urlpatterns = [
    path("signup/", views.signup, name="signup"),
]

Now, we need to include this urls in the main urls.py file. So open urls.py of mysite.

path("accounts/", include("user.urls", namespace="accounts")),

[Run the development server and see the changes]