如何在Django中将两个模型字段表示为一个表单字段? [英] How to represent two model fields as one form field in Django?

查看:272
本文介绍了如何在Django中将两个模型字段表示为一个表单字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法弄清楚如何在Django中正确处理以下情况:



我有一个模型中的日期范围,我存储为两个单独的字段 date_start date_end

  start_date = models.DateTimeField()
end_date = models.DateTimeField()

在此模型的表单中,我想将其代表为一个字段,其中包含一个标签:

 code> timespan = forms.Field(widget = widgets.SelectDateRangeWidget(),label =Date Range)


$ b现在,我扩展了MultiWidget来创建 SelectDateRangeWidget

  class SelectDateRangeWidget(forms.MultiWidget):
...

其中然后加入两个 Date 小部件。我想使用它,但是将其清理成两个单独的模型字段,并且还保留将初始数据加载到表单字段的能力。是每次手动将初始化设置为这两个字段的值的唯一方法,也许在 __ init __ 表单,还可以手动将其清理成两个模型字段,或者是否有更清洁(可以这么说)的方法?

解决方案

似乎在django中使用当前的小部件API是不可能的。这张票是最古老的django门票之一,年龄为7岁: https://code.djangoproject.com /票/ 27



您可以从模型表单中排除原始的2个字段,创建一个新字段并覆盖表单的保存方法。


I can't seem to figure out how to handle the following situation properly in Django:

I have a date range in a model, which I store as two separate fields, date_start and date_end:

start_date = models.DateTimeField()
end_date = models.DateTimeField()

In the form for this model, I want to represent this as one field, with one label:

timespan = forms.Field(widget=widgets.SelectDateRangeWidget(), label="Date Range")

As it is now, I extended MultiWidget to create the SelectDateRangeWidget:

class SelectDateRangeWidget(forms.MultiWidget):
    ...

Which then incorporates two Date widgets. I want to use this, but then clean it into two separate model fields, and also preserve the ability to load initial data into the form field. Is the only way to manually set initial to the value of those two fields every time, maybe in the __init__ function of the form, and also manually clean it into those two model fields, or is there a cleaner (so to speak) way to do this?

解决方案

It seems it is not possible in django using current widgets API. The ticket is one of the oldest django tickets, it is 7 years old: https://code.djangoproject.com/ticket/27 .

You may exclude original 2 fields from the model form, create a new field and override form's save method.

这篇关于如何在Django中将两个模型字段表示为一个表单字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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