mrpopo
mrpopo

Reputation: 1563

Django: URL pattern to include values from multiple fields

I'm fairly new to python and I'm trying to build a URL pattern that takes two fields as parameters. This is part of my model:

CATEGORY_CHOICES = (
    ('M', 'Music'),
    ('G', 'Games'),
    ('T', 'TV'),
    ('F', 'Film'),
    ('O', 'Misc'),
)
category = models.CharField(max_length = 1, choices = CATEGORY_CHOICES)
slug = models.SlugField(unique=True, max_length=255)

What I want to achieve is to be able to call a such as: thisblog.com/music/this-post where /music is the category and /this-post is the slug.

I had an attempt but I can't figure out how to do it properly:

urlpatterns = patterns('',

url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'blog.views.index'),
url(r'^(?P<category>[\w\-]+)/(?P<slug>[\w\-]+)/$', blog_post, name = 'blog_post'),

)

This gives me a 'NoReverseMatch at /' error.

Any help is greatly appreciated :)

UPDATE:

In my html template I have a link:

<p><a class="btn btn-default" href="{{post.get_absolute_url}}" role="button">Read more &raquo;</a></p>

get_absolute_url is defined as:

    def get_absolute_url(self):
        return reverse ('blog.views.post', args = [self.slug])

Upvotes: 0

Views: 1560

Answers (2)

tomwalker
tomwalker

Reputation: 338

If you are using class based views then something like this would work:

# views.py

class ViewPost(DetailView):
    model = Post  #  change this to the model

    def get_queryset(self):
        queryset = super(ViewQuizListByCategory, self).get_queryset()
        return queryset.filter(category=self.kwargs['category'])

# urls.py
from .views import ViewPost
...
url(r'^(?P<category>[\w\-]+)/(?P<slug>[\w\-]+)/$', 
    ViewPost.as_view(), 
    name='blog_post'),
...

The template will be post_detail.html and would be placed as <project_root>/post/templates/post/post_detail.html

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599778

You have two errors in your get_absolute_url method. Firstly, you need to use the URL's name attribute since you have defined it. And secondly, you need to provide both parameters: category as well as slug.

So it should be:

return reverse('blog_post', args=[self.category, self.slug])

Upvotes: 2

Related Questions