django中的Form和ModelForm中的问题

django的Form组件中,如果字段中包含choices参数,请使用两种方式实现数据源实时更新

方法一:重写构造方法,在构造方法中重新去获取值
class UserForm(forms.Form):
    name=fields.CharField(label='用户名',max_length=32)
    email=fields.EmailField(label='邮箱')
    u_id=fields.ChoiceField(
    choice=[]
    )
    def __init__(self,*args,**kwargs):
        super(UserForm.self).__init__(*args,**kwargs)
    #根据UserType表中的更新过的用户类型重新获取更新后的UserType中的数据   self.fields[
'u_id'].choice=models.UserType.object.all().value_list('id','title')

方式二: ModelChoiceField字段
from django.forms import Form
from django.forms import fields
from django.forms.models import ModelChoiceField
class UserForm(Form):
  name = fields.CharField(label='用户名',max_length=32)
  email = fields.EmailField(label='邮箱')
  ut_id = ModelChoiceField(queryset=models.UserType.objects.all())

依赖:
class UserType(models.Model):
  title = models.CharField(max_length=32)

  def __str__(self):
    return self.title

猜你喜欢

转载自www.cnblogs.com/ghl666/p/11470292.html