如何更改ModelForm中所有Django日期字段的默认小部件? [英] How do you change the default widget for all Django date fields in a ModelForm?

查看:332
本文介绍了如何更改ModelForm中所有Django日期字段的默认小部件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一组典型的模型:

# Application A
from django.db import models
class TypicalModelA(models.Model):
    the_date = models.DateField()

 # Application B
from django.db import models
class TypicalModelB(models.Model):
    another_date = models.DateField()

...

如何将所有 DateFields的默认小部件更改为自定义MyDateWidget?

How might one change the default widget for all DateFields to a custom MyDateWidget?

我问,因为我想要我的应用程序有一个jQueryUI datepicker输入日期。

I'm asking because I want my application to have a jQueryUI datepicker for inputting dates.

我已经考虑过使用自定义窗口小部件扩展django.db.models.DateField的自定义字段。这是实施这种全面变更的最佳方式吗?这样的改变将需要专门为每个模型导入一个特殊的MyDateField,这是劳动密集型的,容易出现开发人员错误(即几个模型.DateField将会通过),在我看来,似乎是不必要的重复工作。另一方面,我不喜欢修改可以被认为是典型版本的模型.DateField。

I've considered a custom field that extends django.db.models.DateField with my custom widget. Is this the best way to implement this sort of across-the-board change? Such a change will require specifically importing a special MyDateField into every model, which is labour intensive, prone to developer error (i.e. a few models.DateField's will get through), and in my mind seems like unnecessary duplication of effort. On the other hand, I don't like modifying what could be considered the canonical version of models.DateField.

想法和输入是赞赏。

推荐答案

您可以在 ModelForm 类中声明一个属性,称为 formfield_callback 。这应该是一个将Django模型 Field 实例作为参数的函数,并返回一个表单 Field 实例来表示它的形式。

You can declare an attribute on your ModelForm class, called formfield_callback. This should be a function which takes a Django model Field instance as an argument, and returns a form Field instance to represent it in the form.

然后你需要做的是看看传入的模型字段是否是一个 DateField ,如果是,返回您的自定义字段/窗口小部件。如果没有,模型字段将有一个名为 formfield 的方法,您可以调用该方法返回其默认表单字段。

Then all you have to do is look to see if the model field passed in is an instance of DateField and, if so, return your custom field/widget. If not, the model field will have a method named formfield that you can call to return its default form field.

所以,如下所示:

def make_custom_datefield(f):
    if isinstance(f, models.DateField):
        # return form field with your custom widget here...
    else:
        return f.formfield()

class SomeForm(forms.ModelForm)
    formfield_callback = make_custom_datefield

    class Meta:
        # normal modelform stuff here...

这篇关于如何更改ModelForm中所有Django日期字段的默认小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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