gpt4 book ai didi

python - Django Forms - 如何使表单输入类型等于 "date"

转载 作者:太空宇宙 更新时间:2023-11-03 20:37:23 24 4
gpt4 key购买 nike

我正在使用 django 表单创建两个日期输入。在 html 中创建时,输入类型设置为 type="text"。我怎样才能用 type="date"创建这些论文呢?

表单.py

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

View .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})

搜索.html

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

最佳答案

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

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

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

class DateDateField(forms.DateField):
<b>input_type = 'date'</b>

然后您可以将其用作:

class searchForm(forms.Form):
datestart = forms.DateField(widget=<b>DateDateInput</b>, label='Date Start')
dateend = forms.DateField(widget=<b>DateDateInput</b>, 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>

关于python - Django Forms - 如何使表单输入类型等于 "date",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57084218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com