Django、ModelChoiceField() 和初始值 [英] Django, ModelChoiceField() and initial value

查看:22
本文介绍了Django、ModelChoiceField() 和初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这样的东西:

I'm using something like this:

field1 = forms.ModelChoiceField(queryset=...)

如何让我的表单显示选定的 a 值?

How can I make my form show the a value as selected?

推荐答案

如果你想设置默认初始值,你应该定义 initial 与其他表单字段一样,除了您 将其设置为 ID .

If you want to set the default initial value you should be defining initial like other form fields except you set it to the id instead.

假设你有这样的 field1:

class YourForm(forms.Form):
    field1 = forms.ModelChoiceField(queryset = MyModel.objects.all() )

然后您需要在创建表单时设置初始值,如下所示:

then you need to set initial when you create your form like this:

form = YourForm(initial = {'field1': instance_of_mymodel.pk })

而不是:

form = YourForm(initial = {'field1': instance_of_mymodel })

我还假设您已经为模型定义了 __unicode__ 以便正确显示.

I'm also assuming you've defined __unicode__ for your models so this displays correctly.

这篇关于Django、ModelChoiceField() 和初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆