Django registration form

Django registration form

Django registration form: In our previous tutorial, we have discuss a lot about register as a admin in Django site using User model. To use this feature more conveniently we need to learn how to create registration form using model. To do so we need to create model form using User model. So that user can easily register himself using GUI rather than command prompt.

If you want to learn about User model(previous tutorial), you can visit the link below:

Django Registration

What we will do next?

  1. Create a new file in app folder i.e. forms.py .
  2. Setup views for that form.
  3. Create HTML file which contains <form> tag i.e. actually display to the user.
  4. Setup views if there is an POST request.
  5. Don’t forget to setup URLs for registration view.

Django registration form

So it is the time to perform all above mentioned steps. So let’s start by creating new file forms.py in app folder. Here is the folder tree of firstproject :

Django registration form
Django registration form

Step 1: Create model form using inbuilt User model

firstproject > myapp > forms.py

from django import forms
from django.contrib.auth.models import User

class userForm(forms.ModelForm):
    class Meta():
        model = User
        fields = '__all__'

Step 2: Setup views for that form

firstproject > myapp > views.py

from django.shortcuts import render
from .forms import userForm

def index(request):
    form = userForm()
    return render(request,'index.html',{'uform':form})

Step 3: Create HTML file which contains <form> tag

firstproject > templates > index.html

<!DOCTYPE html>
{% load staticfiles %}
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Registeration Form</title>
    <link rel="stylesheet" href="{% static "bootstrap/css/bootstrap.min.css"%}">
  </head>
  <body>
    <div class="container bg-dark py-3">
      <div class="row">
        <div class="col-md-6 py-3 mx-auto bg-light" style='border-radius:10px;'>
          <form method="post">
            {{ uform }}
          </form>
        </div>
      </div>
    </div>
  </body>
</html>

Step 4: Setup URLs for the view

firstproject > firstproject > urls.py

from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index,name='index'),
]

Output:

Here is the output of the above code:

Django registration form
Django registration form

Explanation:

  • As you can see in the output above, the form is not looking so good.
  • It displays all fields of User model because we have select all fields in forms.py file using ‘__all__’.
  • Now we will select specific fields and convert it into bootstrap form.
  • Also we will add submit button and csrf_token to that form.

Step 5: Formatting form

Let’s beautify this form by selecting specific fields and adding bootstrap to it:

firstproject > myapp > forms.py

from django import forms
from django.contrib.auth.models import User

class userForm(forms.ModelForm):
    password = forms.CharField(widget= forms.PasswordInput())
    #Above line is to make password not visible i.e. <input type="password">
    class Meta():
        model = User
        fields = ('username','email','password')

firstproject > templates > index.html

<!DOCTYPE html>
{% load staticfiles %}
{% load bootstrap4 %}
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Registeration Form</title>
    <link rel="stylesheet" href="{% static "bootstrap/css/bootstrap.min.css"%}">
  </head>
  <body class='bg-dark'>
    <div class="container py-3 my-5">
      <div class="row">
        <div class="col-md-6 py-3 mx-auto bg-light" style='border-radius:10px;'>
          <h2 class='alert alert-secondary text-center'>Registeration Form</h2>
          <form method="post">
            {% csrf_token %}
            {% bootstrap_form uform %}
            <input type="submit" class='btn btn-success'>
          </form>
        </div>
      </div>
    </div>
  </body>
</html>

Output:

Django registration form
Django registration form

As you can see it is Looking nicer than previous one.Now let’s learn actual registration when there is an POST request.

Setup views if there is an POST request

firstproject > myapp > views.py

from django.shortcuts import render
from django.http import HttpResponse
from .forms import userForm

def index(request):
    form = userForm()
    if request.method == 'POST':
        form = userForm(data=request.POST)
        if form.is_valid():
            print("Validation Successfully")
            form.save()
            return HttpResponse("<h1 style='color:green'>Thanks For Registeration</h1>")
    return render(request,'index.html',{'uform':form})

Explanation:

  • AS you can see first of all check whether there is an POST method or not.
  • Which means user clicks on submit button or not.
  • If user clicks on submit button, further we have to check for validations.
  • The data will save if and only if the data is valid.
  • Below is the output for the above code.

Output:

As you can see in the output below, the form returns an error if the data is not valid:

1. If data is not valid

Django registration form
Django registration form

It returns error because, the user named “aman” already exits.

2. If data is valid

I am registering with name “admin”. It returns HttpResponse as below:

Django registration form
Django registration form

3. Admin panel

Download source code

Download project on Github
Download project on Github 

So, it is all about Django registration form. I hope you guys enjoyed the post, Thanks!!!

14 thoughts on “Django registration form

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. An impressive share, I just given this onto a colleague who was doing a little bit evaluation on this. And he in reality ordered me breakfast due to the fact I discovered it for him.. smile. Consequently allow me alter that: Thanks for the deal with! Having said that yeah thanks for spending the time to chat about this, I really feel strongly about it and adore reading additional on this topic. If possible, as you turn into expertise, would you mind updating your weblog with additional details? It?s quite useful for me. Giant thumb up for this internet page publish!

  2. Hmm it looks like your blog ate my first comment (it was extremely long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog. I too am an aspiring blog writer but I’m still new to the whole thing. Do you have any suggestions for novice blog writers? I’d definitely appreciate it.

  3. I simply want to mention I am new to blogging and truly savored your page. More than likely I’m going to bookmark your website . You absolutely have fantastic stories. With thanks for sharing with us your web page.

  4. Thanks for the thoughts you talk about through this web site. In addition, a lot of young women who become pregnant tend not to even try to get medical health insurance because they worry they probably would not qualify. Although a few states currently require that insurers offer coverage no matter what about the pre-existing conditions. Prices on these kind of guaranteed options are usually higher, but when thinking about the high cost of medical care it may be your safer route to take to protect your current financial potential.

  5. Hi there, just became alert to your blog through Google, and found that it’s really informative. I?m going to watch out for brussels. I will appreciate if you continue this in future. Lots of people will be benefited from your writing. Cheers!

  6. We absolutely love your blog and find many of your post’s to be exactly what I’m looking for. can you offer guest writers to write content in your case? I wouldn’t mind writing a post or elaborating on some of the subjects you write in relation to here. Again, awesome website!

  7. hi!,I love your writing so much! share we be in contact more about your post on AOL? I require an expert on this space to unravel my problem. Maybe that’s you! Taking a look forward to look you.

  8. Revolutional update of captcha solution package “XRumer 16.0 + XEvil”:
    captchas regignizing of Google (ReCaptcha-2 and ReCaptcha-3), Facebook, BitFinex, Bing, Hotmail, SolveMedia, Yandex,
    and more than 8400 another types of captchas,
    with highest precision (80..100%) and highest speed (100 img per second).
    You can use XEvil 4.0 with any most popular SEO/SMM software: iMacros, XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other software.

    Interested? You can find a lot of impessive videos about XEvil in YouTube.

    FREE DEMO AVAILABLE!

    See you later!

  9. I do believe all of the ideas you have introduced on your post. They’re very convincing and will certainly work. Nonetheless, the posts are too quick for novices. May just you please lengthen them a little from subsequent time? Thank you for the post.

  10. Several shape classes are furnished with django-registration-redux, masking common instances for accumulating account facts and implementing common constraints for consumer registration. Those bureaucracy had been designed with django-registration-redux’s default backend in thoughts, however may also be beneficial in other situations.This is an amazing post i visible. I have to way to you to proportion it

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.