目前,我有以下2个下拉菜单来显示年份和周,但我想分别在这些菜单中显示当前年份和当前周。
Django表格
from django import forms
class DropDownMenuForm(forms.Form):
week = forms.ChoiceField(choices=[(x,x) for x in range (1,53)])
year = forms.ChoiceField(choices=[(x,x) for x in range (2016,2021)])
显示菜单的模板
<form id="search_dates" method="POST" action="{{ action }}"> {% csrf_token %}
<div class="row">
<div style="display:inline-block">
<h6>Select year</h6>
<select name="select_year">
<option value={{form.year}}></option>
</select>
</div>
<div style="display:inline-block">
<h6>Select week</h6>
<select name="select_week">
<option value={{form.week}}></option>
</select>
</div>
<button type="submit">Search</button>
</div>
</form>
显示当前周和年
from datetime import date
date.today().isocalendar()[1]
date.today().year
如何连接显示当前周和年代码与模板,以便在下拉菜单中查看当前年份和周?
答案 0 :(得分:2)
您可以为表单字段设置initial值:
from datetime import date
from django import forms
class DropDownMenuForm(forms.Form):
week = forms.ChoiceField(choices=[(x,x) for x in range (1,53)], initial=date.today().isocalendar()[1])
year = forms.ChoiceField(choices=[(x,x) for x in range (2016,2021)], initial=date.today().year)
答案 1 :(得分:0)
您可以使用initial =“”属性设置默认值。请参阅Django Docs
中的示例from django import forms
class CommentForm(forms.Form):
name = forms.CharField(initial='Your name')
url = forms.URLField(initial='http://')
comment = forms.CharField()
f = CommentForm(auto_id=False)
print(f)
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" required /></td></tr>
<tr><th>Url:</th><td><input type="url" name="url" value="http://" required /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" required />
</td></tr>