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:
!(#)
[!(#)](#)
YouTip