2

I'm trying to use one view to resolve two url patterns, by using optional parameters in the view definition. I'm following recomendations from this post and this other question.

Here's my code for the url patterns urls.py:

urlpatterns = patterns('myapp.views',
    url(r'^(?P<slug>[\w-]+)/$', 'my_view', name='main_url'),
    url(r'^(?P<slug>[\w-]+)/(?P<optional>[\w-]*)/$', 'my_view', name='optional_url'),
)

And the definition of the view:

def my_view(request, slug, optional=None):

Everything works fine, as far as displaying the templates according to the url patterns. However, when I try to display links using model permalinks, it breaks. I'm following the way of getting a model absolute url as explained in django docs.

Here's the code of my model:

class MyModel(models.Model):
    name = models.CharField(max_length=128)
    slug = models.CharField(max_length=32)

    @models.permalink
    def get_absolute_url(self):
        return ('main_url', [self.slug])

The problem is that get_absolute_url returns an url with two arguments. So I'm getting something like this domain.com/slug// instead of this domain.com/slug/

How can I get the absolute url without the second argument? Is there something I'm doing wrong?

Thanks

Community
  • 1
  • 1
mantish
  • 6,598
  • 2
  • 16
  • 9

1 Answers1

0

You return a list in your get_absolute_url function, that's why you get two parameters. You could just do like so:

class MyModel(models.Model):
    name = models.CharField(max_length=128)
    slug = models.CharField(max_length=32)

    @models.permalink
    def get_absolute_url(self):
        return "/%s/" % self.slug
Ole
  • 1,363
  • 12
  • 22
  • Tanks Ole. That would work for sure, but I wouldn't be using the permalink function. Isn't here a way od making it work using permalink()? – mantish Nov 06 '11 at 20:09
  • That one should be just as good as a permalink, and it's what I personally use to get the urls for my own Django applications. To be honest i'm not quite sure what that `@models.permalink` decorator is used for, but the above function should be all you need, a permalink is really just what it says "a permanent link" – Ole Nov 07 '11 at 08:49