如何在Django中将两个模型字段表示为一个表单字段?

编程入门 行业动态 更新时间:2024-10-20 04:05:29
本文介绍了如何在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岁: code.djangoproject /票/ 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: code.djangoproject/ticket/27 .

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

更多推荐

如何在Django中将两个模型字段表示为一个表单字段?

本文发布于:2023-11-24 22:41:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1627171.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   表单   中将   模型   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!