模型表单集和日期字段
我在模型上有一个模型表单集,其中包含几个日期字段 - 这又是模型中的 DateTimeField。 但当它显示在模板中时,它显示为文本字段。 如何将其显示为下拉框?
WFormSet = inlineformset_factory(UserProfile, W, can_delete=False,exclude=[<list of fields to be excluded>], extra=3)
这就是我初始化模型表单集的方式。
我如何覆盖这些设置
I have a model formset on a model with a couple of date fields - which again is a DateTimeField in the model.
But when it displays in the template, it is shown as a text field.
How can I show it as a drop down box ?
WFormSet = inlineformset_factory(UserProfile, W, can_delete=False,exclude=[<list of fields to be excluded>], extra=3)
This is how I am intializing the modelformset.
How do I override these settings
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常的方法是 覆盖 ModelForm 定义中的默认字段类型。
如果您的模型中有一个 DateField,则下面的示例将起作用(我注意到您有一个 DateTimeField...我稍后会回到这个问题)。 您将指定与通常指定的字段类型完全相同的字段类型,但您将向表单字段构造函数传递一个不同的小部件。
据我所知,Django 1.0.x 中没有为
DateTimeField
提供等效的小部件。 在这种情况下,您需要创建一个自定义小部件,可能是SelectDateWidget
的子类。 我通过对SelectDateTimeWidget
的快速谷歌搜索发现,还有其他几个人一直在制作您正在寻找的小部件。 我没有使用过它们,所以买者自负,但是类似 这个 SelectDateTimeWidget patch< /a> 可能是一个很好的起点。编辑:当使用 ModelFormset 或 InlineModelFormset 时,您仍然可以通过将
form=MyModelForm
传递给inlineformet_factory
函数来实现此目的:这是有效的,因为两个模型表单集工厂实际上调用常规他们自己的实现中的
formset_factory
构造函数。 这有点难以弄清楚,因为文档中没有明确说明...相反,Django 文档通过提及模型表单集工厂扩展了正常的 formset_factory 来暗示这种能力。 每当我有疑问时,我都会打开 django/forms/models.py 来检查表单集工厂函数的完整签名。The usual way to do this is to override the default field types in your ModelForm definition.
The example below would work if you had a DateField in your model (I note you have a DateTimeField... I'll come back to that in a sec). You're going to be specifying the exact same field type as would normally be specified, but you'll pass a different widget to the form field constructor.
There isn't, to my knowledge, an equivalent widget provided for the
DateTimeField
in Django 1.0.x. In this case, you'll want to make a custom widget, perhaps subclassingSelectDateWidget
. I note from a quick google onSelectDateTimeWidget
that there have been several others who've been making what appear to be the widget you're seeking. I've not used them, so caveat emptor, but something like this SelectDateTimeWidget patch might be a good place to start.Edit: When using a ModelFormset or InlineModelFormset, you can still achieve this by passing
form=MyModelForm
to theinlineformet_factory
function:This works because the two model formset factories actually call the regular
formset_factory
constructor in their own implementations. It's a little hard to figure out because it's not explicitly stated in the docs... rather the Django docs allude to this ability by mentioning in passing that the model formset factories extend the normal formset_factory. Whenever I'm in doubt, I opendjango/forms/models.py
to check out the full signature of the formset factory functions.