Why are Django Forms so helpful and easy to use?

Saumya ShahSaumya Shah
2 min read

Table of contents

After learning Flask, it has been quite a few months since I started using Django. And clearly, it makes your work easier. Let it be Django forms, authentication, or its ORM, every aspect of development gets covered.

Till now, I tried quite a few Django features related to forms, some of which I've listed below:

(1) Django forms

(i) mentioning fields in your models

(ii) creating the form parameters in forms.py

(iii) implementing it in your templates through views.py using Jinja syntax

(2) Django UserCreation Forms

This exclusive feature is where you get a ready-made signup form from Django.

from django.contrib.auth.forms import UserCreationForm

The following block of code represents how simple it gets for authentication as well by using UserCreationForm.

def signup(request):
    name = 'signup'
    if request.method == 'POST':
        frm = UserCreationForm(request.POST)
        name = request.POST.get('username')
        if frm.is_valid():
            user = frm.save(commit=False)
            user.username = user.username.lower()
            user.save()
            context = {'name': name}
            login_dj(request, user)
            return render(request, 'cart/publish.html', context)
        else:
            messages.error(request, 'Error creating account as username already exists')
            return render(request, 'cart/login.html')
    form_s = UserCreationForm()
    context = {'form_s': form_s, 'name': name}
    return render(request, 'cart/login.html', context)

It can be used in templates in many ways, but I generally like the below one

<form action="" method="post">
  {% csrf_token %}
  <div class="form-group">
   {{form_s.as_p}}
  <button type="submit">Signup</button>
  <p>Already have an account ?</p>
    <p>  <a href="{% url 'login' %}">Login Here !</a> </p>
  </div>
</form>

Though there might be a styling problem in your website, which is solvable.

(3) Easy to get the user input details

def signup(request):
    name = 'signup'
    if request.method == 'POST':
        frm = UserCreationForm(request.POST)

These are just a handful of features/benefits of Django forms, but using them makes your work easier and a little less complicated.

2
Subscribe to my newsletter

Read articles from Saumya Shah directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Saumya Shah
Saumya Shah

I build fullstack and backend applications. Over the past two years, I've worked with various technologies in this field, developing a strong foundation through projects and study of core concepts. I like learning about distributed systems and automations, an area where I continue to expand my knowledge over the time.