YouTip LogoYouTip

Django Form Component

The Django Form component is used to initialize a page, generate HTML tags, and additionally, it can validate data submitted by users (displaying error messages). **Error Message Display Order:** * First, the error messages from the field attributes are displayed, followed by the error messages from the local hooks. * If the error message from the field attributes is displayed, the error message from the local hooks will not be displayed. * If there are global hooks, they will only start validation after all data has been validated, and the error messages from the global hooks will always be displayed. To use the Form component, you first need to import forms: from django import forms !(#) Next, we create a `My_forms.py` file in the `app01` directory: ## app01/My_forms.py from django import forms from django.core.exceptions import ValidationError from app01 import models class EmpForm(forms.Form): name = forms.CharField(min_length=4, label="Name", error_messages={"min_length": "Too short","required": "This field cannot be empty!"}) age = forms.IntegerField(label="Age") salary = forms.DecimalField(label="Salary") **Field Attributes:** * **label**: The text information displayed before the input box. * **error_message**: Custom error messages to display. The attribute value is a dictionary, where `required` is the key for setting the error message displayed when the field cannot be empty. ## app01/views.py from django.shortcuts import render, HttpResponse from app01.My_Forms import EmpForm from app01 import models from django.core.exceptions import ValidationError # Create your views here. def add_emp(request): if request.method=="GET": form = EmpForm() return render(request,"add_emp.html",{"form": form}) else: form = EmpForm(request.POST) if form.is_valid(): # Perform data validation # Validation successful data = form.cleaned_data# The successfully validated values are placed in cleaned_data. data.pop('r_salary') print(data) models.Emp.objects.create(**data) return HttpResponse( 'ok' ) # return render(request, "add_emp.html", {"form": form}) else: print(form.errors)# Print error messages clean_errors = form.errors.get("__all__") print(222, clean_errors) return render(request,"add_emp.html",{"form": form,"clean_errors": clean_errors}) Add the following rule to the `app01/urls.py` file: path('add_emp/', views.add_emp) HTML Template: ## app01/add_emp.html

Add Employee

{#1. Manually write the HTML page#}

Name:

Age:

Salary:

{#2. Use the form object's as_p method#} {##} {# {% csrf_token %}#} {# {{ form.as_p }}#} {# #} {##} {#3. Manually get the form object's fields#} {##} {# {% csrf_token %}#} {#
#} {# #} {# {{ form.name }} {{ form.name.errors.0 }}#} {#
#} {#
#} {# #} {# {{ form.age }} {{ form.age.errors.0 }}#} {#
#} {#
#} {# #} {# {{ form.salary }} {{ form.salary.errors.0 }}#} {#
#} {# #} {##} {#4. Use a for loop to display all fields#} {##} {# {% csrf_token %}#} {# {% for field in form %}#} {#
#} {# #} {# {{ field }} {{ field.errors.0 }}#} {#
#} {# {% endfor %}#} {# #} {##} The running result is shown in the following image: !(https://static.jyshare.com/images/mix/Django-forms_1.gif) ### Local Hooks and Global Hooks Define the Form class: ## app01/My_forms.py from django import forms from django.core.exceptions import ValidationError from app01 import models class EmpForm(forms.Form): name = forms.CharField(min_length=5, label="Name", error_messages={"required": "This field cannot be empty!", "min_length": "Username is too short."}) age = forms.IntegerField(label="Age") salary = forms.DecimalField(max_digits=5, decimal_places=2, label="Salary") r_salary = forms.DecimalField(max_digits=5, decimal_places=2, label="Please enter salary again") def clean_name(self): # Local hook val =self.cleaned_data.get("name") if val.isdigit(): raise ValidationError("Username cannot be purely numeric") elif models.Emp.objects.filter(name=val): raise ValidationError("Username already exists!") else: return val def clean(self): # Global hook to confirm if the two salary inputs match. val =self.cleaned_data.get("salary") r_val =self.cleaned_data.get("r_salary") if val == r_val: return self.cleaned_data else: raise ValidationError("Please confirm if the salaries match.") The code for the `views.py` file: ## app01/views.py def add_emp(request): if request.method=="GET": form = EmpForm()# Initialize the form object return render(request,"add_emp.html",{"form":form}) else: form = EmpForm(request.POST)# Pass the data to the form object if form.is_valid(): # Perform validation data = form.cleaned_data data.pop("r_salary") models.Emp.objects.create(**data) return redirect("/index/") else: # Validation failed clear_errors = form.errors.get("__all__")# Get global hook error messages return render(request,"add_emp.html",{"form": form,"clear_errors": clear_errors}) The template file code is as follows: ## app01/add_emp.html {% csrf_token %}
{{ form.name }} {{ form.name.errors.0 }}
{{ form.age }} {{ form.age.errors.0 }}
{{ form.salary }} {{ form.salary.errors.0 }}{{ clear_errors.0 }}
{{ form.r_salary }} {{ form.r_salary.errors.0 }}{{ clear_errors.0 }}
The running result is shown in the following image: !(#) [!(#)](#)
← Os TempnamDjango Orm 2 β†’