我有一个模型中的日期范围,我存储为两个单独的字段 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中将两个模型字段表示为一个表单字段?
发布评论