I have created a registration form using the class models.User (refer) in Django as follows:

from Django.shortcuts import render, redirect
from django.contrib.auth.models import User

def register(request):
    if request.method == 'POST':
        username = request.POST['username']
        email = request.POST['email']
        password = request.POST['password']
        confirm_password = request.POST['confirm_password']

        if password == confirm_password:
            # some code
            user = User.objects.create_user(username=username, email=email, password=password)
            user.save()
            return redirect('login')

        else:
            return redirect('register')

    return render(request, 'register.html')

My problems:

  1. Now I want to make Full Name as optional but all other fields as required, also I want to apply length constraint on my fields, how can I do that? As this is an inbuilt model (class models.User), I am not sure how to set blank=True or use max_length for any field.

  2. Also I want to remove the spaces (if any) at the end and beginning of the entered data, before saving it using user.save() (e.g. if someone entered the name as " abc efg " I want to save it as "abc efg"). Basically, I want to use .is_valid() feature of the Django forms. I even tried doing that as:

    from django.shortcuts import render, redirect
    from django.contrib.auth.models import User
    
    def register(request):
        if request.method == 'POST':
            form = User(request.POST or None)
            if form.is_valid():
                #my code
            else:
                return redirect('register')
        return render(request, 'register.html')
    
    

but this is giving me the following error: 'User' object has no attribute 'is_valid'

Any ideas about how can I make the fields optional/required and set the max_length of the fields & remove the trailing spaces (if any) all while using the inbuilt model class models.User?