Dr Mouse
Dr Mouse

Reputation: 331

Django : cannot reverse URL to generate sitemaps

I am currently trying to generate a sitemaps.xml using Django. To do that, i followed the Django documentation but I have troubles to generate the sitemaps for the following type of urls :

url(r'^duo/(?P<pseudo>[a-z]+)/$','clients.views.duo', name='duo')

My sitemaps.py is looking like that :

from django.contrib import sitemaps
from django.core.urlresolvers import reverse

from datetime import datetime

class SiteSitemap(sitemaps.Sitemap):

def __init__(self, names):
    self.names = names

def items(self):
    return self.names

def changefreq(self, obj):
    return 'weekly'

def location(self, obj):
    return reverse(obj)

and the part containing the sitemaps in urls.py like that:

sitemaps = {
'pages':SiteSitemap(['homepage',
                    'landing_page',
                    'mentions',
                    'no_anim',
                    ]),
}

urlpatterns += [
     url(r'^sitemap\.xml', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
]

When passing 'duo' on its own, I have the following error:

NoReverseMatch at /sitemap.xml

Reverse for 'duo' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['duo/(?P<pseudo>[a-z]+)/$']

and when I try to pass arguments in this way ('duo', 'anna'), I have the error:

NoReverseMatch at /sitemap.xml

Reverse for '('duo', 'anna')' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

I am encountering a syntax error which is rather logic as reverse() does not accept triple parenthesis. However, I do not see how I can fix this. Does anyone have a clue about it ?

Upvotes: 0

Views: 834

Answers (3)

Dr Mouse
Dr Mouse

Reputation: 331

Using the previous answers, I did this little piece of code, hope it can be of any help for others users:

def location(self, obj):
    if len(obj) == 1:
        return reverse(obj[0])
    else:
        return reverse(obj[0],args=[obj[1]])

obj are tuple objects declared in urls.py

Upvotes: 0

Shahul Hameed
Shahul Hameed

Reputation: 404

Redefine your location method to following :

def location(self, item):
    return reverse('url_name', args=(arg,))

Upvotes: 0

Alasdair
Alasdair

Reputation: 309109

In this case, the correct syntax for using reverse is:

reverse('duo', args=['anna'])

Upvotes: 1

Related Questions