Search code examples
djangoformsdjango-modelsdjango-formsdjango-formtools

django forms is_valid() method always returning true if all the form field's required is false


models.py created a model registerForm.my database is mysql.

from django.db import models

class registerForm(models.Model):
    name = models.CharField(max_length=50 )
    username = models.CharField( max_length=50)
    email = models.EmailField(max_length=50)
    password = models.CharField(max_length=50)
    class Meta:
        db_table = 'userForm'
    def __str__(self):
        return self.name    

forms.py

from django import forms
from django.forms import widgets
from login_and_logout.models import registerForm

class regForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        # first call parent's constructor
        super(regForm, self).__init__(*args, **kwargs)
        # there's a `fields` property now
        self.fields['name'].required = False
        self.fields['username'].required = False
        self.fields['email'].required = False
        self.fields['password'].required = False

    class Meta: 
        model = registerForm
        fields = "__all__"

views.py

check form is valid using is_valid() method 
    def signup(request):
    
        if request.method == 'POST':
            form = regForm(request.POST)

            print(form.is_valid())
    
            if form.is_valid():
                return HttpResponse('success')
            else:
                return  HttpResponse('fail')
        form = regForm()
        return render(request, 'signup.html', {'form': form})

i trying to implement form validation using javascript in client side and serverside validation in dajngo . in order to acheive form validation without required attribute i give required false in dajngo forms.py. but after the is_valid() method always returning true. but if i remove the init funtion i used to remove requied field in forms.py the is_valid() works. i want to remove the required field and also i want to work the is_valid() method.


Solution

  • You print(print(form.is_valid()) statement for valid form wasn't under any conditional statement to check whether the condition was fulfil for saving a valid form, that was why it return True.

     def signup(request):
            if request.method == 'POST':
                form = regForm(request.POST)
                # This where your conditional check for valid form starts from
                # So you are suppose to put the print statement below the condition if statement 
                # All the logic of validations starts from the if statement
                if form.is_valid():
                    print(form.is_valid())
                    data = form.save(commit=False)
                    data.username = request.user 
                    # whatever data that you want to check for validation  before saving it.
                    data.save()
                    return HttpResponse('success')
                else:
                    return  HttpResponse('fail')
            form = regForm()
            return render(request, 'signup.html', {'form': form})