• 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 2024
  • 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
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

[Step-by-Step] Create a Django SignUp Registration Form with Database

Aniruddha Chaudhari/19188/11
Django

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 SignUp Registration Form?

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

Create Sign Up Form

First of all, create a URL for your signup 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'), # newly added
]

We are going to use the Django forms to create the signup 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.

django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
 
class SignUpForm(UserCreationForm):
    class Meta:
        model = User
        fields = ('username', 'password1', 'password2', )

Create a view to process the signup data and save that data into the database. 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 directory.

{% 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 what the signup 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 nice.

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 a new field for the mobile number.

django.contrib.auth.models import User

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 Signup page, it will look 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 a new model named Profile in models.py.

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

Note: Here, the field “user” is inherited from the Django “User” model using the relationship model field- OneToOneField. 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 the Django database through the 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 signup registration form.

If you get any difficulties while creating the 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.

Comments

  • Reply
    Naaja
    January 27, 2021 at 6:40 pm

    Hello,
    I am working on a project called Voice Based Email System.
    And I need some answers.
    The first one is that how we fill the form input field using voice means when I speak something form field to fill with it.
    And my next question is How to Post data into a database with voice command means when I say post HTML button automatically clicked.

    Appreciated any Help

    Thanks

    • Reply
      Aniruddha Chaudhari
      January 28, 2021 at 9:05 am

      Hi Naaja, very interesting project.

      You can display the buttons on your email form. Each button for recording subject, to, message. When the user clicks on the button that says the record message button, ask the user to speak and record the audio. Convert audio into text and save it.

      You can also save recording audio as a multimedia file in Django

      Best Wishes!

  • Reply
    Sag
    January 11, 2022 at 6:00 pm

    Hi bro thanks for sharing
    Actually in my case newly added user isn’t saving to Users DB.
    Kindly help if possible!
    Its throwing this error!
    django.contrib.auth.models.User.account.RelatedObjectDoesNotExist: User has no account.

    • Reply
      Aniruddha Chaudhari
      January 26, 2022 at 11:18 pm

      Hi Sag,

      Looks like the account model is not updated in the backend. Your migration is not completely done.

      Try running migration

      – python manage.py makemigrations
      – python manage.py migrate

      • Reply
        Biloliddin
        February 28, 2022 at 2:02 pm

        Thanks for keeping it simple.

  • Reply
    Sana Peri
    February 23, 2022 at 5:05 pm

    You have to add from django.contrib.auth.models import User in forms.py

    • Reply
      Aniruddha Chaudhari
      July 9, 2022 at 3:18 pm

      Thanks, Sana for notifying me. Corrected.

  • Reply
    Lyli
    July 1, 2022 at 6:18 pm

    I finished this tutorial. I changed the line:

    Profile.objects.update_or_create(user=user, defaults={'mob': user.profile.mob,)

    to

    Profile.objects.update_or_create(user=user, defaults={'mob': user.profile.mob},)

    since it seems to have a typo. Everything seemed to run properly. I then went to your tutorial on

    and everything seems to run properly, then I followed your tutorial “How to Add Model to Django Admin Site.” I now get an error after clicking the “sign up” button, “’User’ object has no attribute ‘profile’.” The error message refers me to the line: “user.profile.mob = form.cleaned_data.get(‘mob’),” in views.py.

    I have been unable to determine why this isn’t working.
    Thank you for your assistance.

    • Reply
      Aniruddha Chaudhari
      July 2, 2022 at 3:59 pm

      Hi Lyli, thanks for notifying that typo. I have corrected that.

      Regarding the error you are facing, there can be a couple of reasons. From the error, it looks like the table has not been created with the name “profile”. Hope you are following the proper database migrations steps. Check your database table through the Django admin dashboard.

  • Reply
    Mahmood
    September 29, 2022 at 5:22 am

    Hi Aniruddha,

    Nice article, but I have one question: where is “user.profile.mob” defined?

    • Reply
      Aniruddha Chaudhari
      October 4, 2022 at 3:28 pm

      Thanks, Mahmood!

      Here, “user.profile.mob” is the model field defined in the Profile model.

Leave a Reply Cancel reply

Prerequisite for Django

Learn Python Basics

Django Tutorials

Why Django?

Django- Create Your First Project

Django- Adding CSS/Static Files

Django- Use/Load Static Files

Django- Create Form

Django- Create Input-Tags

Django- Display Message on Form Submit

Django- MultipleChoiceField in Form

Django- Read Model Data (order_by)

Django- Read First/Last Queryset Object

Django- Update Model Field

Django- Signals

Django- Create TextField in Form

Django- Add Model to Admin Site

Django- Customize Admin Site

Django- Understanding Model User

Django- Registration/Signup Form

Django- Form Layout with Widget-Tweaks

Django- OneToOneField in Model

Django- Foreign Key & Reverse Lookup

Django- Custom Template Filters

Django- Interactive Shell

Django- Social Login

Django- Deploy and Host [FREE] 🔥

© 2022 – 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