zoukankan      html  css  js  c++  java
  • Django的模型与表单

    在平常的web开发中,我们经常需要提交表单。然而在Django中已经为你准备好了表单类。

    /forms.py
    from django import forms
    from form.models import *
    
    #自定义的表单
    # class NameForm(forms.Form):
    #     FirstName = forms.CharField(max_length=20, label = "姓")
    #     SecondName = forms.CharField(max_length=20,label = "名")
    #     # choice_list = [] 下拉列表
    
    #结合模型的数据表单
    class NameModelForm(forms.ModelForm):
        # total_name = forms.CharField(max_length=20, label = "总名称")
        class Meta:
            model = Name
            # fields = '__all__'
            #fielfs 设置转换字段
            fields = ['firstname','secondname']
            # exclude 设置禁用
            exclude = []
            labels = {
                'firstname': '姓',
                'secondname': '名'
            }
    

    首先from django import forms
    表单有两种实现方式,一种是自定义表单,继承forms.Form类,然后自定义表单字段(这个和定义模型挺像的)

    #自定义的表单
    class NameForm(forms.Form):
        FirstName = forms.CharField(max_length=20, label = "姓")
        SecondName = forms.CharField(max_length=20,label = "名")
        # choice_list = [] 下拉列表
    

    还有一种是使用结合模型的数据表单,他继承了form.ModelForm类,可以自己自动设置需要从模型中转换的字段

    #结合模型的数据表单
    class NameModelForm(forms.ModelForm):
    	#自己添加其他字段
        # total_name = forms.CharField(max_length=20, label = "总名称")
        class Meta:
            model = Name
            # fields = '__all__'
            #fields 设置转换字段
            fields = ['firstname','secondname']
            # exclude 设置禁用
            exclude = []
            #设置表单前的label
            labels = {
                'firstname': '姓',
                'secondname': '名'
            }
    

    当然如果不嫌烦的话可以在HTML页面中使用硬编码(不建议)

  • 相关阅读:
    数据库ACID
    tcp ip detatils
    process vs thread
    C++ virtual descructor
    static_cast dynamic_cast const_cast reinterpret_cast总结对比
    Meta Programming
    C++ traits
    c++内存管理
    洛谷 P4136 谁能赢呢?
    洛谷 P1166 打保龄球
  • 原文地址:https://www.cnblogs.com/yfc0818/p/11072634.html
Copyright © 2011-2022 走看看