Django choices下拉列表绑定实例
Models内容
fromdjango.dbimportmodels fromdjangoimportforms #Createyourmodelshere. classSysConfigForm(forms.Form): DatabaseType=forms.ChoiceField(choices=[('sqlserver','SQLServer'),('oracle','Oracle')]) classUserInfo(forms.Form): vip_type=((0,u'普通用户'),(1,u'高级用户'),) vip=forms.CharField(widget=forms.widgets.Select(choices=vip_type,attrs={'class':'form-control','with':'25px'}),) classMonths(forms.Form): list=((1,u'一月'),(2,u'二月'),(3,u'三月'),(4,u'四月'),(5,u'五月'),(6,u'六月'), (7,u'七月'),(8,u'八月'),(9,u'九月'),(10,u'十月'),(11,u'十一月'),(12,u'十二月'),) obj_month=forms.CharField(widget=forms.widgets.Select(choices=list,attrs={'class':'form-control'}),) classUserUsesSourceForm(forms.Form): #somefieldshere SOURCES_CHOICES=( ('A','A'), ('E','E'), ) username=forms.CharField(label=("Username"),max_length=30,help_text=("Required")) provider=forms.ChoiceField(widget=forms.Select(),choices=SOURCES_CHOICES,initial=SOURCES_CHOICES[1])
Views内容
fromdjango.shortcutsimportrender,HttpResponse frompollsimportmodels fromdjango.template.loaderimportget_template #Createyourviewshere. defindex(request): obj=models.UserInfo() ifrequest.method=='POST': user_obj=models.UserInfo(request.POST) ifuser_obj.is_valid(): print(user_obj.clean()) else: user_error=user_obj.errors print(user_error) returnrender(request,'index.html',{'obj':obj,'user_error':user_error}) months=models.Months() returnrender(request,'index.html',{'obj':obj,'months':months}) #获取下拉列表选中记录 defTest01(request): template=get_template('test01.html') form=models.UserUsesSourceForm(initial={"username":request.user.username,'provider':models.UserUsesSourceForm.SOURCES_CHOICES[1]}) #returnrender_to_response('update_datasource.html',context_instance=RequestContext(request,params)) html=template.render(locals()) returnHttpResponse(html)
Test页面内容
Title {%csrf_token%} {%ifform.non_field_errors%} {%forerrorinform.non_field_errors%}
{{error|escape}}