DJANGO AUTH : Juggling POST request for ‘User’ model

Parthib Deb
6 min readJul 14, 2023

--

Welcome back, everyone!! Today’s topic is a little more fascinating, as you can tell by the name, so without any further delay, let’s get started!!

Whether it is a web app or a mobile app, user authentication is a crucial issue for any client-oriented product. Because of this, offering a robust user-authentication and permission capability is a mandatory feature for every modern framework — Django is not an exception to this rule. It has its own path for handling it; after all, we are aware that there is an admin panel incorporated into the software that allows us to view every user’s tracks and datas , as well as their account history !! Django already has a built-in user model for verification of users — ( path : from django.contrib.auth.models import User) . The user model consists of all these fields : username , email , password , first_name(blank=True) , last_name(blank=True) and many more methods. Django informs us that first_name and last_name are not mandatory fields to fill out ; however, there will be some default garbage values to be filled in in the database. It only focuses on the user’s username, email, and password (it will throw an exception if a new user’s username is found to be identical to an existing one; but for email and password validation, we must write our own logic). This is the simplest version of user model , inherited from AbstractUser model , which also comes from AbstractBaseUser model . Seems like the tree got a deep root on its underneath !! Isn’t it?? Now here comes a question!! — How to use this simplest , yet beautiful gift from django — see, there are many ways to handle it ; depends upon the situation and the necessities that you expects from the model, here I want to put some light on two different categories of views logics to handle POST request — WITH FORM , WITHOUT FORM

  1. WITH FORM : We know that , django is already a fullstack framework from its birth. So, it provides a very good interface to handle HTML forms that will take input values according to the fields declared in the models — ModelForm. A ModelForm is a very Convenient approach to just simply set-up this connection rather than having to create separate forms classes based on the model fields and connect with the label-names of the HTML form tags. so , there are two modelforms that we can use — UserCreationForm or Own ModelForm.

Despite the fact that , the user model has numerous built-in modelforms of this type ,I’d like to make this conversation light, while still explaining the distinctions . So I am stick with these two forms only for this discussion.

  1. A. UserCreationForm (Path — from django.contrib.auth.forms import UserCreationForm) :
#forms.py

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

class UserRegistrationForm(UserCreationForm):
class Meta:
model = User
fields = "__all__"
'''
fields of UsercreationForm : username , email ,
password1, password2(confirmation)
'''

Here we can see , that UsercreationForm consists of only 4 fields — username , email , password , confirm password . That means, this basic form very much focuses on username as well as password verification. Quite impressive!!! Django is just showering blessings!! But here you can see there are no fields for user’s first_name and last_name (although, user model have those fields). so now , if you want to add user’s names sections— then you have to make some changes in the parent model of user , that is the AbstractUser (if you wish to work with UserCreationForm)

#models.py

from django.contrib.auth.models import AbstractUser

class NewUser(AbstractUser):
first_name=models.Charfield(max_length=150)
last_name=models.Charfield(max_length=150)

# add any other fields if you want to

def __str__(self):
return self.username

#settings.py

AUTH_USER_MODEL = 'APP_NAME.NewUser'
#as we have created a new user model for this project only

#forms.py

from django.contrib.auth.forms import UserCreationForm
from myapp.models import *

class CustomUserRegistrationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = NewUser
fields = UserCreationForm.Meta.fields + ("custom_field",)

Clearly, we can see that we are altering our AbstractUser model and creating a new User model for our particular project, and we see that the changes are reflected everywhere (from specifying the new user model’s name in settings to the forms file).

  1. B. Own ModelForm (path: from django.forms import ModelForm) : Otherwise, if we don’t want to go with UserCreationForm , we can create our own ModelForm, like we do for other custom models . Here we have to remind that , we just want to use the fields of the given user model’s fields without any extra facilities.
#forms.py
from django.contrib.auth.models import User
from django import forms

class UserRegistrationForm(forms.Modelform):
class Meta:
model = User
fields = "__all__"
'''
Fields are : username, email, password, first_name, last_name
'''

Although , we can use first and last_name fields of user, which is helful for showing user’s identity in front-end , for sending emails , but here password verification is missing !! Maybe it is true that- sometimes a blessings also comes with some cost!! We maynot have the direct access to some pre-dominant validations if we use the model is this way (but yeah!! it’s all depends on situations!!)

For all the ways incorporating django-forms, the common and bare views logics will be same (I told bare!! because, yeah you must add some other stuffs in your views to upgrade your logic , but this is the skeleton — if you use forms)

#views.py ( for all types of forms )

from django.contrib.auth.models import User
from .forms import *
from django.shortcurts import render,redirect

def signIn(request):
form=UserRegistrationForm()
if request.method == "POST:
form=UserRegistrationForm(request.POST)
if form.is_valid():
form.save(commit=False) # make sure that you have redefined this method
# in forms.py
#Otherwise
'''
User.objects.create_user(
username=request.POST['username'],
email=request.POST['email'],
password=request.POST['password'] # after validation
)
User.first_name=request.POST['first_name']
User.last_name=request.POST['last_name']
User.save()
# without using 'request.POST' as a raw dictionary , you can use
# form.cleaned_data['___'], specially if you want to redirect in signin page
'''
#some redirect page
else:
return render(request,"signin.html",{"form":form})

This clearly demonstrates that, we are using either ‘request.POST’ dictionary or ‘form.cleaned_data[‘___’]’ to get specific data. Else , we can use create api without using create_user to provide the dataset as a collection.

2. WITHOUT FORM : It’s the most minimum and classic way to handle the input data without any hectic , here we just have to make sure that the <label for = “___” , name = “__”> must be matches with specific model field-names.

views.py of my USER-AUTH project (without forms)

From my code , you can clearly understand that we just have to use the robust way of creating object by taking data from request.POST dictionary and calling queryset apis. Here I have not made any changes in in models or forms (although, I tried to use forms) , so it’s a primitive USER-AUTH obviously!!

This was all about my viewpoint on how to handle POST request in authentication. On the top of this codes and logics, you can add your viewpoint to make it more better in terms of security and validations. Hope you have realized my words and what I want to tell. Will meet you in my next Blog!!

--

--