• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2021
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools

[Step-by-Step] Create a Django Sign Up Registration Form | Example

Aniruddha Chaudhari/1665/0
Django
YouTube CSEstack

In this tutorial, we are going to use the default Django User for creating our sign up and registration form.

We are considering our project name as MyProject and app name as Core. If you are copying code from this tutorial, change the wording MyProject and Core with your project name and app name respectively.

How to Create a Django Sign Up Registration Form?

Let’s start creating registration form step-by-step with simple example.

Create Sign Up Form

First of all, create a URL for your sign up page by adding a new path to the urlpatterns list in urls.py.

from . import views
from django.conf.urls import url, include
from django.urls import path

urlpatterns = [
    url(r'^$', views.index, name='home'),
    path('signup/', views.signup, name='signup'), #added
]

We are going to use the Django forms to create the sign up form.

If you are new to Django form, refer Django form tutorial.

Create forms.py file if it is not present and add the following class for the sign-up form.

For creating sign up form, we can use the Django UserCreationForm.

from django.contrib.auth.forms import UserCreationForm

class SignUpForm(UserCreationForm):
    class Meta:
        model = User
        fields = ('username', 'password1', 'password2', )

Create a view to processing the signup data. You can simply copy below function definition in your views.py file.

from .forms import SignUpForm

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()  
            # load the profile instance created by the signal
            user.save()
            raw_password = form.cleaned_data.get('password1')

            # login user after signing up
            user = authenticate(username=user.username, password=raw_password)
            login(request, user)

            # redirect user to home page
            return redirect('home')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form})

Create a sign-up HTML page in your template directorry.

{% extends 'base.html' %}
 
<h2>Sign up</h2>
 <form method="post">
    {% csrf_token %}
    {% for field in form %}
      <p>
        {{ field.label_tag }}<br>
        {{ field }}
        {% if field.help_text %}
          <small style="color: grey">{{ field.help_text }}</small>
        {% endif %}
        {% for error in field.errors %}
          <p style="color: red">{{ error }}</p>
        {% endfor %}
      </p>
    {% endfor %}
    <button type="submit">Sign up</button>
  </form>

{% endblock %}

Run your Django project locally. Open the below URL in your browser.

http://127.0.0.1:8000/signup/

This is how the sign up form will look like.

Django sign up registration form

Wow!

This is simple, isn’t it?

You can add CSS code to customize the UI and to make it look nicely.

We have just considered the username and password for the sign-up form. We might want to ask the user for more data for registration like a mobile number. In this case, you can add extended fields to your Django sign up registration form.

Let’s see.

Add Extended Fields

Update the Django form by adding new field for mobile number.

class SignUpForm(UserCreationForm):
    mob = forms.IntegerField(max_length=11) # newly added
    class Meta:
        model = User
        fields = ('username', 'mob', 'password1', 'password2', )
        labels = {'mob': 'Mobile Number',} # newly added

If you run the Django project and open the Sign up page, it will loook like this.

Django sign up registration form with extended fields

Even though the mobile number field is visible on the registration form, there is no provision to store that field value.

Instead of saving this data in the default Django User model, we are creating a new Profile model where we will be saving all the other extended reaeration fields.

Create Profile Model

Creating new model named Profile in models.py.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    mobile = models.IntegerField()

Note: Here, field user is inherited from the Django User model. In this case, if the user gets deleted from the default Django User model, his/her profile data also will get deleted.

When the user submits the registration form, we have to save the data into the profile model.

Update the signup view in your views.py file.

from .forms import SignUpForm

#newly added function
def update_user_data(user):
    Profile.objects.update_or_create(user=user, defaults={'mob': user.profile.mob,)

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()

            #newly added
            user.profile.mob = form.cleaned_data.get('mob')
            update_user_data(user)  

            # load the profile instance created by the signal
            user.save()
            raw_password = form.cleaned_data.get('password1')

            # login user after signing up
            user = authenticate(username=user.username, password=raw_password)
            login(request, user)

            # redirect user to home page
            return redirect('home')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form})

From the signup form, we are calling update_user_data, to save the extended user profile information.

You can see all the registered users in Django admin dashboard. For that you have to add model “Profile” in the Django admin.

You can also provide a feature in your registration form to allow users to sign up with Social media like Facebook, Gmail, LinkedIn, Twitter, etc.

Congratulations! Your registration form is ready.

That’s all from the Django sign up registration form.

If you get any difficult while creating registration form, ask me in the comment section below. I’m happy to help you. Keep learning!

Python Interview Questions eBook

Django
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Leave a Reply Cancel reply

Prerequisite for Django

Learn Python Basics

Django Tutorials

Django- Create Your First Project

Django- Adding CSS/Static Files

Django- Create Form

Django- Create TextField in Form

Django- Add Model to Admin Site

Django- Registration/Signup Form

Django- Interactive Shell

Django- Social Login

© 2021 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard