Quick Contact

    Python Tutorial
    Python Panda Tutorial
    Python Selenium
    Python Flask Tutorial
    Python Django
    Numpy
    Tensorflow
    Interview Questions & Answers

    Django Forms Validation

    Form validation means verification of form data. Form validation is an important process when we are using model forms. When we validate our form data, we are actually converting them to python datatypes. Then we can store them in the database.

    This validation is necessary since it adds that layer of security where unethical data cannot harm our database.

    There are certain JavaScript Validation methods too, that can be easier to implement, but they are not preferred at all as JavaScript is client-side scripting. If the client browser does not have JavaScript enabled, the data will not be validated. And, it causes some serious issues for developers.

    Therefore, data validation on the server side is always necessary. Though, you can have JavaScript validation on the client side.

    There are different ways of form validation we can use.

    1. Validation of a Particular Field

      When we want certain fields to be validated, this method is used. We have to follow some Django conventions at this point to define our methods and other things.

      In our forms.py file, add these lines of code:

      Code:

      #Validation #Ducatindia
      defclean_password(self):
      password = self.cleaned_data['password']
      iflen(password)<4:
      raiseforms.ValidationError("password is too short")
      return password
      
    2. Some important points to note:

      • The name of the function is special. You have to define it for each field you want to validate.
      • Syntax:

        clean_fieldname()

      • Then we used self.cleaned_data[‘field_name’]
      • This is also specific to a particular field. This list contains the cleaned data received from the form. The cleaned data means its in python data-type format. It allows us to use python functions on the data we stored in a variable.

      • After that, we used some conditions. The more important part is that we raised an error. The error messages can be customized.
      • ValidationErrors are built in methods and subclasses of Django. They are used in models too.

      • Always remember to return the data. It doesn’t matter if the data is changing or not, this function should always return the data on which it is operated. That data may or may not be changed.
    3. Using is_valid()

      You can use is_valid() when required to validate complete form-data. This validation will check for Python-datatypes. This function will return True or False (Python Data Types) in return.

      Let’s edit our view function a little bit to demonstrate that.

      Code:

      fromdjango.shortcuts import render
      from .import forms
      #Ducatindia #Form #View Functions
      defregform(request):
      form = forms.SignUp()
      ifrequest.method == 'POST':
      form = forms.SignUp(request.POST)
      html = 'we have recieved this form again'
      ifform.is_valid():
      html = html + "The Form is Valid"
      else:
      html = 'welcome for first time'
      returnrender(request, 'signup.html', {'html': html, 'form': form})
      
    4. Validation using Validators

      We will now learn a professional way of form validation. It is very easy to use and provide much more control over fields.

      Let’s modify our forms.py again.

      Code:

      fromdjango import forms
      fromdjango.core import validators
      #Ducatindia #Form
      classSignUp(forms.Form):
      first_name = forms.CharField(initial = 'First Name', )
      last_name = forms.CharField(required = False)
      email = forms.EmailField(help_text = 'write your email', required = False)
      Address = forms.CharField(required = False, )
      Technology = forms.CharField(initial = 'Django', disabled = True)
      age = forms.IntegerField(required = False, )
      password = forms.CharField(widget = forms.PasswordInput, validators = [validators.MinLengthValidator(6)])
      re_password = forms.CharField(widget = forms.PasswordInput, required = False)
      
    5. Custom Validators

      Suppose you have some fields which you want to validate and there may be no built-in validator of your use-case. Then, you can create your own custom validators.

      1. Just declare a function with the parameter value. The parameter name shall be that.
      2. Then, perform your desired validations on value. When value satisfies any criteria raise a ValidationError
      3. Add that function_name in validators argument of the chosen field, just as we used validators.
    6. For example, edit your forms.py

      Code:

      fromdjango import forms
      fromdjango.core import validators
      #Ducatindia #Custom_Validator
      defcheck_size(value):
      iflen(value)<6:
      raiseforms.ValidationError("the Password is too short")
      #Ducatindia #Form
      classSignUp(forms.Form):
      first_name = forms.CharField(initial = 'First Name', )
      last_name = forms.CharField(required = False)
      email = forms.EmailField(help_text = 'write your email', required = False)
      Address = forms.CharField(required = False, )
      Technology = forms.CharField(initial = 'Django', disabled = True)
      age = forms.IntegerField(required = False, )
      password = forms.CharField(widget = forms.PasswordInput, validators = [check_size, ])
      re_password = forms.CharField(widget = forms.PasswordInput, required = False)
      

     

    Apply now for Advanced Python Training Course

    Copyright 1999- Ducat Creative, All rights reserved.

    Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.