Django表单-如何使表单输入类型等于“日期”

时间:2019-07-17 21:22:15

标签: python html django forms date

我正在使用Django表单为日期创建两个输入。使用html创建时,输入类型设置为type =“ text”。我该如何使用type =“ date”创建论文。

forms.py

class searchForm(forms.Form):
    datestart = forms.DateField(label="Date Start")
    dateend = forms.DateField(label='Date end')

views.py

def search(request):
    if request.method == 'POST':
        form = searchForm(request.POST)
        if form.is_valid():
            print(form)
    else:
        form = searchForm()
    return render(request, 'next_launch/search.html',{'form': form})

search.html

    <form action="search" method="post">
        {% csrf_token %}}
        {{ form }}
    <input type="submit" value="Submit">
    </form>

1 个答案:

答案 0 :(得分:0)

您可以在小部件的attrs中修补类型,例如:

class searchForm(forms.Form):
    datestart = forms.DateField(
        widget=forms.DateInput(attrs={'type': 'date'}),
        label='Date Start'
    )
    dateend = forms.DateField(
        widget=forms.DateInput(attrs={'type': 'date'}),
        label='Date end'
    )

如果您想更频繁地使用它,可以制作自己的小部件,例如:

class DateDateField(forms.DateField):
    input_type = 'date'

然后您可以将其用作:

class searchForm(forms.Form):
    datestart = forms.DateField(widget=DateDateInput, label='Date Start')
    dateend = forms.DateField(widget=DateDateInput, label='Date end')

这将呈现如下形式:

>>> print(searchForm())
<tr><th><label for="id_datestart">Date Start:</label></th><td><input type="date" name="datestart" required id="id_datestart"></td></tr>
<tr><th><label for="id_dateend">Date end:</label></th><td><input type="date" name="dateend" required id="id_dateend"></td></tr>