英文:
Django daterangefield in a form
问题
You can use the "DateInput" widget in your Django form to display the "electable_time" field as a date field that allows users to pick a date from a calendar. Here's how to update your form in Chinese:
forms.py
from django import forms
from django.forms import DateInput # Import DateInput widget
class CreateCommissionElection(forms.ModelForm):
class Meta:
model = CommissionElection
fields = ['electable_time',]
widgets = {
'electable_time': DateInput(attrs={'type': 'date'}),
}
这个更改将使用 "DateInput" 将 "electable_time" 字段显示为日期字段,允许用户从日历中选择日期。
英文:
I have a model looking like this:
models.py
class CommissionElection(models.Model):
electable_time = DateRangeField()
And my form looks like this:
forms.py
class CreateCommissionElection(forms.ModelForm):
class Meta:
model = CommissionElection
fields = ['electable_time',]
Right now the electable time displays like this:
What widget is needed to make the fields datefields instead of charfields, so you can pick a date out of a calendar instead of writing it out?
答案1
得分: 1
你可以为date
字段指定不同的小部件:
from django.forms.widgets import DateInput
class MyDateInput(DateInput):
input_type = 'date'
接下来,我们可以为这个字段创建一个DateField
表单字段:
from django.forms.fields import DateField
class MyDateField(DateField):
widget = MyDateInput
然后在DateRangeField
中重用它:
from django.contrib.postgres.forms.ranges import DateRangeField
class MyDateRangeField(DateRangeField):
base_field = MyDateField
然后我们可以将它用作表单字段:
class CreateCommissionElection(forms.ModelForm):
electable_time = MyDateRangeField()
class Meta:
model = CommissionElection
fields = ['electable_time']
英文:
You can specify a different widget for a date
field:
<pre><code>from django.forms.widgets import DateInput
class MyDateInput(DateInput):
<b>input_type = 'date'</b></code></pre>
next we can make a form DateField
field for this:
<pre><code>from django.forms.fields import DateField
class MyDateField(DateField):
<b>widget = MyDateInput</b></code></pre>
and reuse that in a DateRangeField
:
<pre><code>from django.contrib.postgres.forms.ranges import DateRangeField
class MyDateRangeField(DateRangeField):
<b>base_field = MyDateField</b></code></pre>
then we can use this as field:
<pre><code>class CreateCommissionElection(forms.ModelForm):
electable_time = <b>MyDateRangeField()</b>
class Meta:
model = CommissionElection
fields = [
'electable_time',
]</code></pre>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论