django Form的回顾

编程入门 行业动态 更新时间:2024-10-21 19:27:10

<a href=https://www.elefans.com/category/jswz/34/1767634.html style=django Form的回顾"/>

django Form的回顾

  from django.shortcuts  import render
from django.forms  import Form
from django.forms  import fields
from django.forms  import widgets
from django.forms.models  import ModelChoiceField
from rbac  import models

  手动档: class UserInfoModelForm(Form): name = fields.CharField( required= True,  error_messages={ "required":  " 用户名不能为空 "})
    email = fields.EmailField( required= True)

    #  这样写不能时时更新 , 因为它是静态字段 , 只会在声明这个 class 的时候访问数据库一次
    # part = fields.ChoiceField(choices=models.Role.objects.value_list("id","caption"))
    part = fields.ChoiceField()

    def  __init__( self, *args, **kwargs):
        super(). __init__(*args, **kwargs)
        #  此种方式下 , 每次 new form 对象 , 都会执行数据库查询 , 数据时时更新
        self.fields[ "part"].choices = models.Role.objects.value_list( "id",  "caption")   自动档: class UserInfoModelForm(Form):
    name = fields.CharField( required= True,  error_messages={ "required":  " 用户名不能为空 "})
    email = fields.EmailField( required= True)

    #  此种方式和手动挡效果一样 , 但是它会默认将 model_obj 中的 pk 作为 select 选择 option 的 value 值 , 不能配置 , 不推荐使用
    part = ModelChoiceField( queryset=models.Role.objects.all())


def index(request):
    form = UserInfoModelForm()     return render(request,"index.html",{"from":form})      

转载于:.html

更多推荐

django Form的回顾

本文发布于:2024-02-07 01:54:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1752388.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:django   Form

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!