Using modelform form Validation

Source: Internet
Author: User

1. Define model.py

The type of field defined in model is valid only when validated through a form, and the field types in the database are not exactly the same, as there is no IPAddress type in the database. If a field is not validated through a form, the user can enter any type of data on the front-end without error.

 from Import Models class HV (models. Model):    name=models. Charfield (max_length=100,unique=true,primary_key=True)    IP=models. Genericipaddressfield ()    def__str__(self):        return Self.name

2. Define froms.py

Modelform connects the model with the foreground form

Forms. The form is not connected to the back-end model, but is used to determine whether the foreground input is legitimate

 fromDjangoImportForms fromDjango.formsImportModelform fromAptest.modelsImportHv,vm,test#Import the model you want to useclassHvform (modelform):classMeta:model=HV Fields= ['name','IP']        #Fields = ' __all__ ' #选择使用所有字段        #exclude = [' title '] #不适用某个字段
class Vmform (modelform):    CPU# re-formats the CPU field, overwriting the type format defined in model. Custom error message, need to know the name of the specific error such as "requeired" These names can be found in the API         class  Meta:        = vm          '__all__'

3. Edit views.py

defAdd (Request):ifRequest.method = ='POST':        #Print request. post[' Hvname '],request. post[' HVIP ']        PrintRequest.method Form=Hvform (Request. POST)ifForm.is_valid ():#determine if the input data is legitimate            #Print Form            #print form.cleaned_data[' name '],form.cleaned_data[' IP ']FC =Form.cleaned_dataPrintEcx'name'],fc['IP']        Else: Err.append (form.errors)#Output error message    Else: Form=Hvform () context={'Hour_offset': Hour_offset,'ls': LS,'Err': Err}returnRender (Request,'aptest/form.html', context)

4. Edit Template form.html

<!DOCTYPE HTML><HTML><Head>   <title>ADD</title>   <Linkrel= "stylesheet"href= "Http://apps.bdimg.com/libs/bootstrap/3.3.0/css/bootstrap.min.css">   <Scriptsrc= "Http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></Script>   <Scriptsrc= "Http://apps.bdimg.com/libs/bootstrap/3.3.0/js/bootstrap.min.js"></Script></Head><Body><formclass= "Form-horizontal"role= "form"Action=""Method= "POST">{% Csrf_token%}<!--{{form.as_table}} - <!--If you use this method, you will need to render the form to the template in the view, otherwise open the page does not see the input box -   <Divclass= "Form-group">      <label for= "Name1"class= "Col-sm-2 Control-label">Name</label>      <Divclass= "Col-sm-10">         <inputtype= "text"class= "Form-control"ID= "Name1"name= "Name"value= "{{form.name}}">  <!--here value must be defined, and form cannot be rendered into the template. Form.name is the Form=hvform (request) in view. POST), does not define the Value,post data background form cannot receive -      </Div>   </Div>   <Divclass= "Form-group">      <label for= "IP"class= "Col-sm-2 Control-label">Ip</label>      <Divclass= "Col-sm-10">         <inputtype= "text"class= "Form-control"ID= "IP"name= "IP"value= "{{Form.ip}}">      </Div>   </Div>      <Divclass= "Form-group">      <Divclass= "Col-sm-offset-2 col-sm-10">         <Buttontype= "Submit"class= "Btn Btn-default">ADD</Button>      </Div>   </Div></form>{% If err%}<Pstyle= "color:red;">Please correct the error: {{err}} below. </P>{% endif%}</Body></HTML>

Access output:

When the form content is displayed in the template through {{form.as_table}}, Django automatically converts the foreign key field into a control of select, and selects a value from the drop-down box, such as:

context={'err': Err,'form': Form}return Render (Request,'aptest/current_datetime.html', context)

Using modelform form Validation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.