Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

How to validate data entered in the sign up form created in Django?

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():
                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')
    
            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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to declare a form first. If you are using default django user, then you can user UserCreationForm to validate the data:

from django.contrib.auth.forms import UserCreationForm

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST or None)
        if form.is_valid():
           form.save()
           # rest of the code

Now, lets say you want want to clean the data which you get from the HTML form, then you can use clean_<field_name> method. To do that inside UserCreationForm, you can override it(also adding some code to show how to customize forms):

class CustomUserForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') 
    def clean_first_name(self):
       return self.cleaned_data['first_name'].strip()

Please see the documentation for more information on validation and cleaning data in forms.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...