In my django 开发者_如何学Capp,I need to create a dropdownlist for days of month.The view expects a 2 digit value for day(that is 01 and not 1 for first day).I have to pass a list of days to the template sothat the select element's options can be created.
I tried this as given below,and the drop down list is created properly .The day selected, returned as unicode(say u'26' for selection of 26th day) is used in view to compare with datetime.datetime.today().day .Everything works ..Still ,I am worried if this is the correct way to create the list of days..I mean ,extending a list of unicode strings with another list of ints doesn't look right..But,I could not think of a better solution.
Please help me with with suggestions.
thanks
mark.
in views.py
...
days=[u'01',u'02',u'03',u'04',u'05',u'06',u'07',u'08',u'09']
days.extend([x for x in range(10,32)])
...
and in template
...
<form action=".">
...
<select name="day" id="dayselect">
{% for aday in days %}
<option value={{aday}} > {{aday}}</option>
{% endfor %}
</select>
<input type="submit" value="entries of the day" />
</form>
...
the urls.py has
url(r'^entries/(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/$','myapp.views.entries_for_day',
{
'template_name':'myapp/entries_for_day.html',
'page_title':'Entries of the day'
},name='entries_for_day'),
If you want to create strings with leadings zeros you should use string formatting. For example you can look at this answer doing precisely this.
For your example you could use something like this.
days = [u'%02d' % x for x in range(1,32)]
Which creates the list with leading zeros.
Though I'm doubtful of the problem itself. Are you sure you should be able to select all 31 days of months where there are less? - you could simply send a datetime object to the template and output the days for that given month.
But if you insist:
Another option could be sending in a simple list of range(1, 32) and then formatting it in the template:
{% for day in days %} {{ day|stringformat:"02d" }} {% endfor %}
Another is perhaps to make the view accept single digit input aswell.
String interpolation.
days = [u'%02d' % x for x in range(1, 32)]
精彩评论