码迷,mamicode.com
首页 > 其他好文 > 详细

form

时间:2017-04-15 13:57:36      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:get   tar   meta   inf   gets   models   类型   forms   from   

form操作动态select数据

forms.py

from django import forms
from django.forms import fields
from django.forms import widgets
from django.forms.models import ModelChoiceField
from app01 import models
class UserInfoForm(forms.Form):
    user = fields.CharField(
        required=True,
        widget=widgets.Textarea(attrs={class:c1})
    )
    pwd = fields.CharField(
        max_length=12,
        widget=widgets.PasswordInput(attrs={class:c1})
    )
    user_type = fields.ChoiceField(
        # choices=[(1,‘普通用户‘),(2,‘超级用户‘)],
        choices = [],
        # widget = widgets.Select
    )
    user_type2 = fields.CharField(widget=widgets.Select(choices=[]))
    #方式二,models.py中需要加上def __str__(self):return self.name
   user_type3
= ModelChoiceField( empty_label=请选择用户类型, to_field_name=name, queryset=models.UserType.objects.all() ) def __init__(self,*args,**kwargs): super(UserInfoForm, self).__init__(*args,**kwargs) self.fields[user_type].choices = models.UserType.objects.values_list(id,name) self.fields[user_type2].widget.choices = models.UserType.objects.values_list(id,name)

 

views.py

from django.shortcuts import render
from app01.forms import UserInfoForm
from app01 import models
# Create your views here.
def index(request):
    obj = UserInfoForm()
    # obj.fields[‘user_type‘].choices = models.UserType.objects.values_list(‘id‘,‘name‘)
    #类里面的静态字段,必须重新去数据库取值赋值,或者在forms.py中构造函数中取值
    return render(request,index.html,{obj:obj})

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>
        {{ obj.user }}
    </p>
    <p>
        {{ obj.pwd }}
    </p>
    <p>
        {{ obj.user_type }}
        {{ obj.user_type2 }}
    </p>
</body>
</html>

 

form

标签:get   tar   meta   inf   gets   models   类型   forms   from   

原文地址:http://www.cnblogs.com/hongpeng0209/p/6713721.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!