{"id":85770,"date":"2022-01-15T09:00:24","date_gmt":"2022-01-15T03:30:24","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=85770"},"modified":"2022-01-15T09:00:24","modified_gmt":"2022-01-15T03:30:24","slug":"django-form-handling-and-validation","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/","title":{"rendered":"Django Form Handling and Validation"},"content":{"rendered":"<p>In this article, we will learn about forms in Django, form handling and validation. Let&#8217;s start!!!<\/p>\n<h3>What are forms in Django?<\/h3>\n<p>Forms are a set of HTML elements used to collect user input. In simple terms, a form is used whenever you give any kind of instruction or input on the internet.<\/p>\n<p>The input elements are included within <strong>&lt;form&gt;&lt;\/form&gt;<\/strong> tags. An HTML form is a name given to all of them. All of the websites make use of forms, each with its own set of use-cases.<\/p>\n<p>Forms can be found at the following places daily:<\/p>\n<p>1. Conduct a Google search<\/p>\n<p>2. Facebook status updates and stories<\/p>\n<p>3. Registrations over the internet<\/p>\n<p>4. Online Quizzes, Tests, and Other Resources<\/p>\n<p>There are too many examples to list. Forms have evolved into an important component of online applications.<\/p>\n<p>They help us organise and send user data over HTTP. They give the user a variety of input choices.<\/p>\n<h4>Prerequisites<\/h4>\n<p>All prior tutorial topics, including Django Installation and Architecture.<\/p>\n<h3>What exactly is HTTP?<\/h3>\n<p>HyperText Transfer Protocol is an acronym for HTTP. It is a set of rules that all computers on a network must follow to send data to other computers. This protocol is the foundation for all client\/server designs.<\/p>\n<p>The transmission of data through HTTP can be done in a variety of ways. GET and POST are the two most popular techniques among all of them.<\/p>\n<h4>1. GET<\/h4>\n<p>This approach is used for user data that does not affect the website&#8217;s state. GET is a URL technique for sending form data.<\/p>\n<p>The best example is Google search. This method is used to send data that does not modify the database.<\/p>\n<p>When we wish to bookmark pages, the GET technique comes in useful because our search query is included in the URL.<\/p>\n<p>The size of the URL usually limits the GET technique. It is not possible to send anything larger than the URL size. We can only send text requests as a result of this.<\/p>\n<h4>2. POST<\/h4>\n<p>This approach alters the state of the webpage and is used for sensitive data. POST is an HTTP method for sending data as a collective structure. It is delivered by the client as a separate request, similar to cookies, alongside URL requests.<\/p>\n<p>POST data isn&#8217;t the same as a cookie; it&#8217;s a separate kind of resource. As this data is not in a URL, this approach is more secure than fetching. The POST method also has a larger size limit, making it possible to upload files.<\/p>\n<p>On all registration forms and quizzes, this procedure is employed.<\/p>\n<h3>HTML Forms<\/h3>\n<p>Two key attributes are there for the tag:<\/p>\n<ul>\n<li>\n<h4>Action<\/h4>\n<\/li>\n<\/ul>\n<p>This attribute indicates where the form data should be submitted. It can be left empty, but the data will be delivered to the same URL in that case. This attribute simply instructs the form to send the data to the appropriate location.<\/p>\n<ul>\n<li>\n<h4>Method<\/h4>\n<\/li>\n<\/ul>\n<p>The procedure for submitting data is specified by this attribute. For the same, there are POST and GET values. This attribute should be written in all caps.<\/p>\n<h3>Form Handling Process in Django<\/h3>\n<p>Django form handling employs all of the mechanisms we&#8217;ve seen in earlier tutorials (to display data about our models.): the view receives a request, do any necessary actions (reading data from the models is included), and then produces and returns an HTML page (We pass a context containing the data to be shown into a template.)<\/p>\n<p>What complicates things further is that the server must be able to process data provided by the user and redisplay the page if any problems occur.<\/p>\n<p>This is a flowchart that displays how Django handles the form requests.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2022\/01\/form-handling-process-in-django.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-85788\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2022\/01\/form-handling-process-in-django.webp\" alt=\"form handling process in django\" width=\"979\" height=\"726\" \/><\/a><\/p>\n<p>According to this flowchart, form handling in django does the following:<\/p>\n<p>1. The default form will be displayed the first time the user requests it.<\/p>\n<ul>\n<li>If you&#8217;re establishing a new record, the form may include blank fields or be pre-populated with default values. As it is not coupled with any user-entered data at this point, the form is referred to as unbound (though it may have initial values).<\/li>\n<\/ul>\n<p>2. Data from a submitted request is received and bound to the form.<\/p>\n<ul>\n<li>When we bind data to a form, we ensure that the user-entered data and any mistakes are available when the form is re-displayed.<\/li>\n<\/ul>\n<p>3. Validate and clean the data.<\/p>\n<ul>\n<li>Cleaning the data (for example, deleting invalid characters that may send harmful stuff to the server) and turning it to Python types that are consistent.<\/li>\n<li>Validation ensures that the values are appropriate for the field (e.g., within the correct date range, not too short or lengthy, and so on).<\/li>\n<\/ul>\n<p>4. Re-display the form with any user populated values and error warnings for the problem fields if any of the input is incorrect.<\/p>\n<p>5. Perform required steps if all data is valid.<\/p>\n<p>6. Redirect the user to another page after all actions are completed.<\/p>\n<p>Django offers a variety of tools and approaches to aid you in completing the tasks listed above. The Form class is the most basic, as it simplifies both form HTML production and data cleaning and validation. We&#8217;ll go through how forms function in the next part, using the example of a website that allows librarians to renew books.<\/p>\n<h3>Django Form Class<\/h3>\n<p>The Django form class is used to implement forms. Django comes with several built-in jobs, including:<\/p>\n<p>1. Rendering Form<br \/>\n2. Form Validation<\/p>\n<p>There are many others, but we&#8217;ll focus on these two in our guide because they&#8217;re the most important.<\/p>\n<p>Django forms and Django models are extremely similar classes. With forms and associated validations, the Django form class offers a lot of capability. There are numerous built-in forms in this class that you may use to render HTML directly.<br \/>\nLet\u2019s follow the below steps to create a Registration form.<\/p>\n<h4>Step 1: Enable the virtual environment.<\/h4>\n<p>You first have to activate your virtual environment before beginning an application.<\/p>\n<p>Open your PowerShell or Command prompt to enter the following code.<\/p>\n<p>Follow the code to do the same.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">(Virtual Environment name)\\Scripts\\activate.bat<\/pre>\n<p>The above code will activate the environment. The next step is to go to the directory you are planning to work with.<\/p>\n<h4>Step 2: Create a new application.<\/h4>\n<p>In our existing Django Project, we will develop a new application for this course.<\/p>\n<p>Enter the following in the command line:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">python manage.py startapp (Application_name)<\/pre>\n<p>In our case, the application name is <strong>\u201cRegistrationForm\u201d<\/strong>.<\/p>\n<p>Now install it in the settings.py file.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2022\/01\/create-new-app-1.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-85789\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2022\/01\/create-new-app-1.webp\" alt=\"create new app\" width=\"1043\" height=\"432\" \/><\/a><\/p>\n<p>With this, our application is successfully installed.<\/p>\n<h4>Step 3: Working with Forms.py file.<\/h4>\n<p>Create a new python file called forms.py within your RegistrationForm app. You are going to define your form in this file.<\/p>\n<p>Right-click on the application name. Then click on the \u201cNew File\u201d option and name it <strong>\u2018forms.py\u2019<\/strong>.<\/p>\n<h4>Enter the following code in the newly created forms.py file:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from django import forms\n\nclass SignUp(forms.Form):\n\nemployee_name = forms.CharField(help_text = 'Employee_name', )\nemail = forms.EmailField(help_text = 'Enter your Email Id', )\nEmp_Department = forms.CharField(help_text = 'Enter your Department', )\nEmp_contact = forms.IntegerField()\npassword = forms.CharField(widget = forms.PasswordInput)\nre_password = forms.CharField(help_text = 'Re-enter your password', widget = forms.PasswordInput)<\/pre>\n<h4>Understanding the code:<\/h4>\n<p>In line 1, we have imported a Django form class here. We then constructed the SignUp class. It is a subcategory of form. We defined several fields just like models. It&#8217;s nearly the same as the model class.<br \/>\nThe fields will turn into various forms of input when we make them available in the HTML file. Django has several fields for various input elements.<\/p>\n<ul>\n<li>BooleanField<\/li>\n<li>CharField<\/li>\n<li>ChoiceField<\/li>\n<li>DateField<\/li>\n<li>DecimalFieldSome common properties can be used to manipulate these fields. These qualities are useful for data validation. They offer a more restricted data selection.<\/li>\n<\/ul>\n<h4>Required:<\/h4>\n<p>It takes true or false values. It is true, by default, and makes fill in the field mandatory. You can declare it false if you wish to change it.<\/p>\n<h4>Initial:<\/h4>\n<p>The fields have an initial value such as text boxes that are filled with a certain generic text. This is the first argument.<\/p>\n<h4>Help-text:<\/h4>\n<p>We apply help-text if you want a few instructions to show that field. This attribute shows the string in which you pass.<\/p>\n<h4>Disabled:<\/h4>\n<p>We do not want the user to modify particular fields many times. We use the disabled parameter in that instance. It takes Boolean python, true or false. This staticizes the field, i.e. the user cannot alter it.<\/p>\n<h4>Widget:<\/h4>\n<p>Some fields can replicate different types of input. Like CharField for all text inputs, including passwords. With built-in widgets like PasswordInput, we can use a widget attribute.<\/p>\n<h4>Validators:<\/h4>\n<p>When we use data validations, this attribute is useful. The validators are built-in and we can also construct custom validators.<\/p>\n<h4>Label:<\/h4>\n<p>You don&#8217;t have to specify it if you want to see the name of your field as the form. The label is shown as a string before the related form field.<\/p>\n<p>There are many more such attributes, but here the most common ones are discussed.<\/p>\n<h3>The table below lists the most commonly used fields and their descriptions.<\/h3>\n<table>\n<tbody>\n<tr>\n<td><b>Name<\/b><\/td>\n<td><b>Class<\/b><\/td>\n<td><b>HTML input<\/b><\/td>\n<td><b>Value<\/b><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">BooleanField<\/span><\/td>\n<td><span style=\"font-weight: 400\">BooleanField(**kwargs)<\/span><\/td>\n<td><span style=\"font-weight: 400\">CheckboxInput<\/span><\/td>\n<td><span style=\"font-weight: 400\">False<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">CharField<\/span><\/td>\n<td><span style=\"font-weight: 400\">CharField(**kwargs)<\/span><\/td>\n<td><span style=\"font-weight: 400\">TextInput<\/span><\/td>\n<td><span style=\"font-weight: 400\">Whatever you specified for\u00a0<\/span><\/p>\n<p><span style=\"font-weight: 400\">&#8217;empty_value.&#8217;<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">DateTimeField<\/span><\/td>\n<td><span style=\"font-weight: 400\">DateTimeField(**kwargs)<\/span><\/td>\n<td><span style=\"font-weight: 400\">DateTimeInput<\/span><\/td>\n<td><span style=\"font-weight: 400\">None\u00a0<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">DateField<\/span><\/td>\n<td><span style=\"font-weight: 400\">DateField(**kwargs)<\/span><\/td>\n<td><span style=\"font-weight: 400\">DateInput<\/span><\/td>\n<td><span style=\"font-weight: 400\">None<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">ChoiceField<\/span><\/td>\n<td><span style=\"font-weight: 400\">ChoiceField(**kwargs)<\/span><\/td>\n<td><span style=\"font-weight: 400\">Select<\/span><\/td>\n<td><span style=\"font-weight: 400\">\u201c \u201c (empty string).<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">EmailField<\/span><\/td>\n<td><span style=\"font-weight: 400\">EmailField(**kwargs)<\/span><\/td>\n<td><span style=\"font-weight: 400\">EmailInput<\/span><\/td>\n<td><span style=\"font-weight: 400\">\u201c \u201c (empty string).<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">ImageField<\/span><\/td>\n<td><span style=\"font-weight: 400\">ImageField(**kwargs)<\/span><\/td>\n<td><span style=\"font-weight: 400\">ClearableFileInput<\/span><\/td>\n<td><span style=\"font-weight: 400\">None<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">DecimalField<\/span><\/td>\n<td><span style=\"font-weight: 400\">DecimalField(**kwargs)<\/span><\/td>\n<td><span style=\"font-weight: 400\">NumberInput<\/span><\/td>\n<td><span style=\"font-weight: 400\">None<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">FileField<\/span><\/td>\n<td><span style=\"font-weight: 400\">FileField(**kwargs)<\/span><\/td>\n<td><span style=\"font-weight: 400\">ClearableFileInput<\/span><\/td>\n<td><span style=\"font-weight: 400\">None<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h4>Step 4: Working with views.py file:<\/h4>\n<p>We must now deal with views.py. When passed to HTML, the form will be automatically rendered.<\/p>\n<h4>Add this code in your views.py:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from django.shortcuts import render\nfrom . import forms\n\n\ndef EmpRegForm(request):\n\nform = forms.SignUp()\n\nif request.method == 'POST':\nform = forms.SignUp(request.POST)\nhtml = 'You have already filled the form'\n\nelse:\nhtml = 'Welcome to the Signup form'\nreturn render(request, 'signup.html', {'html': html, 'form': form})<\/pre>\n<h4>The Code: An Overview:<\/h4>\n<p>We declared forms in the above view function the same way we declared models. A new instance of the form class is created. Then we examined which method is being used to receive our form, whether it is the POST method or another.<\/p>\n<p>This is a critical situation. It will determine whether the user is filling out the form for the first time or has previously completed one. We receive a GET request when a user requests a form for the first time, but a POST request is sent after the user submits data in the form. As a result, we will send the appropriate response.<\/p>\n<h4>Step 5: Configuration of the URL<\/h4>\n<p>Now we must create a new file in the &#8220;RegistrationForm&#8221; directory with the name urls.py.<\/p>\n<h4>Add the following code to the urls.py file:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from django.urls import path\nfrom .views import *\n\nurlpatterns = [\n\npath('', EmpRegForm, name = 'registration form'),\n\n]<\/pre>\n<p>Then, in your main urls-config file, make the necessary changes.<\/p>\n<h4>Add this to your urlpatterns list:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from django.contrib import admin\nfrom django.urls import path\nfrom RegistrationForm import views\n\n\nurlpatterns = [\n\npath('admin\/', admin.site.urls),\n\npath('Registration', views.EmpRegForm),\n]<\/pre>\n<h4>Step 6: HTML template creation:<\/h4>\n<p>Now we can start rendering our forms. Make a new folder called templates in your &#8220;RegistrationForm&#8221; directory. Make a new file called signup.html in that folder.<\/p>\n<h4>In signup.html, paste the following code:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;style&gt;\nbody{\nbackground-color:olivedrab;\n}\n&lt;\/style&gt;\n&lt;title&gt;TechVidvan Employee Portal&lt;\/title&gt;\n&lt;\/head&gt;\n&lt;body&gt;\n&lt;pre&gt;&lt;center&gt;\n&lt;h1&gt;Employee Registration Form&lt;\/h1&gt;\n&lt;h3&gt;TechVidvan Employee Portal&lt;\/h3&gt;\n&lt;h2&gt;{{ html }}&lt;\/h2&gt;\n&lt;form action = '' method=\"post\"&gt;\n&lt;!-- Very Important csrf Token --&gt;\n{% csrf_token %}\n&lt;table&gt;\n{{ form.as_table }}\n&lt;\/table&gt;\n&lt;input type=\"submit\" name=\"register\"&gt;\n&lt;\/form&gt;\n&lt;\/center&gt;&lt;\/pre&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;<\/pre>\n<h3>What does the code say?<\/h3>\n<p>We have a general HTML file here. The primary difference begins with the &lt;form&gt; tags. The form tag has two attributes: the action, which is blank, indicating that the page&#8217;s view function will handle all the answers, and the method, which we have set as a post. If an error occurs, use an uppercase POST value.<\/p>\n<p>Then we used the letter <strong>{%csrf_token%}<\/strong>. This is the first time we&#8217;ve used any of Django&#8217;s security features.<\/p>\n<p>Cross-site Request Forgery, or CSRF, is a type of security vulnerability to websites that collect data. Django includes built-in support for this by requiring the use of this token.<\/p>\n<p>Bots can fill out your website forms if you don&#8217;t have a CSRF token. Your web data, on the other hand, may end up on other websites.<\/p>\n<p>Using a CSRF token avoids this. This field contains a value that is created at random by your server and must match that value when the form is submitted. Other servers will reject that value as well. As a result, web data remains where it belongs.<\/p>\n<p>Following that, we used tags. We declared <strong>{{form.as_table}}<\/strong> inside of that. This is how Django handles form templating. More possibilities are available if we declare this as a paragraph.<\/p>\n<p>After that, we created a submit button. Our form will be sent after you click this button.<\/p>\n<p>Now enter the following code in the terminal to run the server:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">python manage.py runserver<\/pre>\n<p>The final <strong>output<\/strong> will look like this:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2022\/01\/final-output.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-85790\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2022\/01\/final-output.webp\" alt=\"final output\" width=\"1920\" height=\"928\" \/><\/a><\/p>\n<h3>Validation of Django Forms:<\/h3>\n<p>Validation of form data is referred to as form validation. When working with model forms, form validation is essential. We&#8217;re converting our form data to Python data types when we validate it. After that, we&#8217;ll be able to store them in the database.<\/p>\n<p>This validation is put in use because it adds a layer of security to our database, ensuring that unethical data cannot harm it.<\/p>\n<h3>NOTE:<\/h3>\n<p>Several JavaScript Validation methods are easier to use, however, they are not recommended because JavaScript is a client-side scripting language. The data will not be validated if the client browser does not support JavaScript. It also causes significant issues for developers.<\/p>\n<p>As a result, server-side data validation is always required. On the client-side, however, JavaScript validation is possible.<\/p>\n<p>Form validation follows the below mentioned ways:<\/p>\n<h4>1. Validation for a Particular Field:<\/h4>\n<p>This method is put in use when we wish to validate specific fields. At this stage, we must abide by Django rules to declare our methods and other items.<\/p>\n<h4>Add the following lines of code to our forms.py file:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#Validation\n\ndef clean_It(self):\n\npassword = self.cleaned_data['password']\n\nif len(password) &lt; 6:\nraise forms.ValidationError(\"Increase the length of the password\")\nreturn password<\/pre>\n<h4><strong>Syntax:<\/strong><\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">clean_fieldname()<\/pre>\n<p>There are a few points to remember:<\/p>\n<ul>\n<li>Then we used <strong>self.cleaned_data[\u2018field_name\u2019]<\/strong><\/li>\n<\/ul>\n<p>This is likewise a field-specific term. This list contains the data from the form that has been cleaned. The data that has been cleaned is now in Python data-type format. It enables us to use Python functions on data stored in a variable.<\/p>\n<ul>\n<li>Following that, we applied some constraints. What&#8217;s more significant is that we made an error. It is possible to customise the error messages.<\/li>\n<\/ul>\n<p>ValidationErrors are Django&#8217;s built-in methods and subclasses. They&#8217;re also employed in models.<\/p>\n<ul>\n<li>This function should always return the data on which it is operated, regardless of whether the data is changing or not. That data may or may not be altered.<\/li>\n<\/ul>\n<p>The user can use the following code, however, it is not recommended for professional use. This solution necessitates a lot more code, which goes against Django&#8217;s principles. Alternatives exist that are far more efficient.<\/p>\n<p>This will be the <strong>result.<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2022\/01\/validation-for-a-particular-field.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-85791\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2022\/01\/validation-for-a-particular-field.webp\" alt=\"validation for a particular field\" width=\"1920\" height=\"843\" \/><\/a><\/p>\n<h4>2. Using the is_valid() method:<\/h4>\n<p>When you need to validate whole form data, you can use is_valid(). Python-data types will be checked throughout this validation. The result of this method is True or False (Python Data Types).<\/p>\n<p>To demonstrate this, let&#8217;s modify our view function a little.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def EmpRegForm(request):\n\nform = forms.SignUp()\n\nif request.method == 'POST':\nform = forms.SignUp(request.POST)\nhtml = 'You have already filled the form'\n\nif form.is_valid():\nhtml = html + \"The Form is Valid\"\n\nelse:\nhtml = 'Welcome to the Signup Form'\nreturn render(request, 'signup.html', {'html': html, 'form': form})<\/pre>\n<p>When we merely want our data to be python type, we commonly use this method. It verifies all of the information. In view functions, we use &#8220;is valid()&#8221; because it returns True and False values directly.<\/p>\n<p>When your form data is valid, the <strong>output<\/strong> of the above code should look like this.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2022\/01\/using-is_valid.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-85792\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2022\/01\/using-is_valid.webp\" alt=\"using is_valid()\" width=\"1920\" height=\"936\" \/><\/a><\/p>\n<h4>3. Using Validators:<\/h4>\n<p>We&#8217;ll now learn how to validate forms professionally. It&#8217;s simple to use and gives you a lot more control over fields.<\/p>\n<p>Let&#8217;s make a few modifications to our forms. py file one more time:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from django import forms\nfrom django.core import validators\n\nclass SignUp(forms.Form):\n\nemployee_name = forms.CharField(initial = 'Employee Name', )\nemail = forms.EmailField(help_text = 'Enter your Email id', required = False)\nEmp_Department = forms.CharField(help_text = 'Enter your Department',required = False)\nEmp_contact = forms.IntegerField(required = False, )\npassword = forms.CharField(widget = forms.PasswordInput, validators = [validators.MinLengthValidator(6)])\nre_password = forms.CharField(widget = forms.PasswordInput, required = False)<\/pre>\n<p>A validator is similar to a callable function. We primarily use them to raise ValidationErrors when certain requirements aren&#8217;t met.<\/p>\n<p>Validators are generic attributes that can be applied to any field. Each field has its own set of validators. We&#8217;re using MinLengthValidator and passing a value of 6 as an argument.<\/p>\n<p>As a result, our password fields must be at least 6 characters long.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2022\/01\/using-validators.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-85793\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2022\/01\/using-validators.webp\" alt=\"using validators\" width=\"1920\" height=\"936\" \/><\/a><\/p>\n<p>This error also has a user-friendly interface and provides thorough information.<\/p>\n<h4>4. Using the Custom Validators:<\/h4>\n<p>Let&#8217;s say you have some fields that need to be validated, but there isn&#8217;t a built-in validator for your use case. After that, you&#8217;ll be able to design your validators.<\/p>\n<ul>\n<li>Simply declare a function with the value of the parameter.<\/li>\n<li>Then, on the value, conduct your desired validations. When a value satisfies any of the conditions, a ValidationError occurs.<\/li>\n<li>Just as we did with validators, add that function name to the validators argument of the chosen field.<\/li>\n<\/ul>\n<p>Edit your forms.py,<strong> for example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">from django import forms\nfrom django.core import validators\n\n\ndef check_size(value):\n\nif len(value) &lt; 6:\nraise forms.ValidationError(\"Increase the length of your password.\")\n\n\nclass SignUp(forms.Form):\n\nemployee_name = forms.CharField(initial = 'Employee Name', )\nemail = forms.EmailField(help_text = 'Enter your Email id', required = False)\nEmp_Department = forms.CharField(help_text = 'Enter your Department',required = False)\nEmp_contact = forms.IntegerField(required = False, )\npassword = forms.CharField(widget = forms.PasswordInput, validators = [check_size, ])\nre_password = forms.CharField(widget = forms.PasswordInput, required = False)<\/pre>\n<p>This will result in the following output:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2022\/01\/using-custom-validators.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-85794\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2022\/01\/using-custom-validators.webp\" alt=\"using custom validators\" width=\"1920\" height=\"936\" \/><\/a><\/p>\n<h3>Summary:<\/h3>\n<p>You may now easily create all of the django forms and collect various types of information from the user. On a website, forms are really useful. They also present a lot of ethical issues because they contain user data. As a result, always create forms in a secure manner that adheres to international standards.<\/p>\n<p>We&#8217;ve learnt all the methods for validating our forms, although the final two are recommended.<\/p>\n<p>Forms can do a lot more. Each task has its built-in form. You can now create a web application on your own. Work on it; it&#8217;ll be enjoyable.<\/p>\n<p>If you have any questions about Django forms and form handling, please leave them in the comments area. We&#8217;ll be happy to assist you in any way we can.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will learn about forms in Django, form handling and validation. Let&#8217;s start!!! What are forms in Django? Forms are a set of HTML elements used to collect user input. In&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":85787,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3383],"tags":[4589,4590,4591],"class_list":["post-85770","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-django","tag-django-form-class","tag-django-form-handling","tag-django-form-validation"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Django Form Handling and Validation - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn about django forms and form class, how to create forms, django form handling &amp; different methods for validating our forms with examples\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Django Form Handling and Validation - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn about django forms and form class, how to create forms, django form handling &amp; different methods for validating our forms with examples\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2022-01-15T03:30:24+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2022\/01\/django-form-handling-and-validation.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"15 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Django Form Handling and Validation - TechVidvan","description":"Learn about django forms and form class, how to create forms, django form handling & different methods for validating our forms with examples","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/","og_locale":"en_US","og_type":"article","og_title":"Django Form Handling and Validation - TechVidvan","og_description":"Learn about django forms and form class, how to create forms, django form handling & different methods for validating our forms with examples","og_url":"https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2022-01-15T03:30:24+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2022\/01\/django-form-handling-and-validation.webp","type":"image\/webp"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"15 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Django Form Handling and Validation","datePublished":"2022-01-15T03:30:24+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/"},"wordCount":2777,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2022\/01\/django-form-handling-and-validation.webp","keywords":["django form class","Django Form Handling","Django Form validation"],"articleSection":["Django Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/","url":"https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/","name":"Django Form Handling and Validation - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2022\/01\/django-form-handling-and-validation.webp","datePublished":"2022-01-15T03:30:24+00:00","description":"Learn about django forms and form class, how to create forms, django form handling & different methods for validating our forms with examples","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2022\/01\/django-form-handling-and-validation.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2022\/01\/django-form-handling-and-validation.webp","width":1200,"height":628,"caption":"django form handling and validation"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/django-form-handling-and-validation\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Django Form Handling and Validation"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/85770","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=85770"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/85770\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/85787"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=85770"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=85770"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=85770"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}