Reputation: 2780
Currently, I have the following 2 Drop-Down menus to display the years and weeks but I want to display the current year and current week, respectively, inside of these menus.
Django form
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)])
Template to display the menus
<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>
Display the current week and year
from datetime import date
date.today().isocalendar()[1]
date.today().year
How can I connect the Display the current week and year code with the template, so I can see the current year and week selected in the dropdown menus?
Upvotes: 0
Views: 2751
Reputation: 39659
You can set initial value for form field:
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)
Upvotes: 2
Reputation: 16
You can set the default using the initial="" attribute. See the example below from the 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>
Upvotes: 0