Django表单中的daterangefield

huangapple go评论56阅读模式
英文:

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:
Django表单中的daterangefield

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 = [
        &#39;electable_time&#39;,
    ]&lt;/code&gt;&lt;/pre&gt;

huangapple
  • 本文由 发表于 2023年5月6日 17:30:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76188146.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定