Blog

    Month abbreviation problem in url using django's generic view

    Published on Oktober 13, 2012

    As I progressed testing my weblogging application, I realized that Django got a URL pattern problem when a blog entry was called by the archive_month generic view, e.g. like this:

    "http://mysite.com/weblog/2010/okt/", which is the german abbreviation for october. But if I browsed "http://mysite.com/weblog/2010/oct/ the server found and showed the page behind the URL.

    The problem is that the locale's abbreviated month name is defaulted to '%b', when the archive_month generic view takes a month_format parameter, which specifies a strftime directive to parse the month value with.

    But strftime uses the POSIX locale which is different from what is set by Django's own locale mechanism for example when the date template filter is used like this:

    {% block content %}
    	<ul>
    	{% for month in date_list %}
    	<li><a href="{% url blog_entry_archive_month year,month|date:"b" %}">
     	    {{ month|date:"F" }}</a>
     	</li>
    	{% endfor %}
    	</ul>
    {% endblock %}

     

    SOLUTION:

    So I decide to fix it by switching to numeric month (01-12) in the URL pattern. To do this

    1. define the URL pattern for your entry page in your urls.py file, note (?P<month>\d{2}), and add month_format='%m'

    from django.conf.urls.defaults import *
    
    from blog.models import Entry
    
    
    entry_info_dict = {
        'queryset': Entry.live.all(),
        'date_field': 'pub_date',
    
    urlpatterns = patterns('django.views.generic.date_based',
         (r'^$','archive_index',entry_info_dict,'blog_entry_archive_index'),
         (r'^(?P<year>\d{4})/$','archive_year',entry_info_dict,'blog_entry_archive_year'),
         (r'^(?P<year>\d{4})/(?P<month>\d{2})/$','archive_month',dict(entry_info_dict, month_format='%m'),'blog_entry_archive_month'),
         (r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$','archive_day',dict(entry_info_dict, month_format='%m'),'blog_entry_archive_day'),
         (r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$','object_detail',dict(entry_info_dict, month_format='%m'),'blog_entry_detail'),
    )

     

    2. change the date template filter from year,month|date:"b" to year,month|date:"m":

    {% block content %}
    	<ul>
    	{% for month in date_list %}
    	<li><a href="{% url blog_entry_archive_month year,month|date:"m" %}">
     	    {{ month|date:"F" }}</a>
     	</li>
    	{% endfor %}
    	</ul>
    {% endblock %}

    For more details about generic views please refer to Django's generic views.

    Comments

    So far, this entry has 0 comments.

    Post a comment

Buchempfehlungen pix pix
Kalender
December 2018
MonTueWedThuFriSatSun
     12
3456789
10111213141516
17181920212223
24252627282930
31      
Über pix

Ich bin Diplom Informatiker und das ist meine persönliche Internet sowie weblog Seite.mehr Informationen...