I am working on a sample project and I have the following scenario. I have 3 views that were initially simple function based views the only difference between them was that each has different query sets based on a slug in the url yet using the same template file which is for listing posts.
Example:
views.py
def index(request):
allposts = Post.objects.order_by('created')
return direct_to_template(request,'postlist.html',{'posts':allposts})
def showcategory(request,slug):
categposts = Post.objects.filter(category__slug=slug).order_by('created');
return direct_to_template(request,"postlist.html",{"posts":categposts})
def showtag(request,tagslug):
posts_with_tag = Post.objects.filter(tags__name__in=[tagslug]).order_by('created')
return direct_to_template(request,"postlist.html",{"posts":posts_with_tag})
urls.py
urlpatterns = patterns('',
url(r'^$','blog.views.index', name='home'),
url(r'^tag/(?P<tagslug>[-\w]+)/$','blog.views.showtag',name='showtag'),
url(r'^(?P<slug>[-\w]+)/$','blog.views.showcategory',name='showcategory'),
)
That looked pretty redundant to me given that all 3 views are returning the same template with different querysets so I though I'll just use generic class based ListView. I also subclassed it for some customization, something like this:
class ListPosts(ListView):
template_name = "postlist.html"
context_object_name="posts"
paginate_by = 5
allow_empty = True
Confident enough, I thought that any query(including using the current route slug) I feed into the queryset property should work, such as this for example:
url(r'^tag/(?P<tagslug>[-\w]+)/$',ListPosts.as_view(
queryset = Post.objects.filter(tags__name__in=['tagslug']).order_by('created')),
name = 'showtag'),
Unfortunately the framework couldn't really understand what 'tagslug' actually would refer to.
So is there any way I can get the value of the slug in the url and use in the query right in the queryset property without having to do that in my view? I could have just done it in my view but if you check my urls above they're pretty different in structure, one does not have a slug, another has only one and another has two, I don't feel that that having conditionals in the view would not be much neat.
Thanks for your time.