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

查看:40
本文介绍了如何更改 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 日期选择器.

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

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

class SomeForm(forms.ModelForm)
    formfield_callback = make_custom_datefield

    class Meta:
        # normal modelform stuff here...

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

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