[EMAIL PROTECTED] wrote: > Hello - > > I'm playing around with a blog application and I want it to have a > tagging feature. I have the usual ManyToMany relationship set up with > Post and Tag (I'm not going to past my model since I think everyone is > familiar with this kind of setup). > > I have three Posts tagged as follows: > > Post1: articles, python, django > Post2: articles, python > Post3: articles, music > > Essentially, I would like to be able to go to a URL like: > > http://blog/tag/articles/python/django > > And get Post1 as a result. > > Likewise, I'd like to go to: > > http://blog/tag/articles/python > > And get Post1 and Post3 as a result. > > I have a URL entry set up as follows: > > (r'^blog/tag/(.*)', 'ssrc.blog.views.tags'),
Using .* in your URL regexes is not recommended, you only want to match what you absolutely need to match. Something like the following would be better: (r'^tags/(?P<url>([a-zA-Z0-9-]+/)+)$', 'ssrc.blog.views.tags') This would only allow one or more tags with each tag consisting of one or more of the characters a-z, A-Z, 0-9, and/or hyphens. The (?P<url> snip ) part creates a named group, so a parameter named url will be passed to your view. > I have my tags view set up like so: > > def tags(request, url=""): > if url: > posts = {} > for post in Post.objects.all(): > for tag in [part for part in url.split("/") if part != ""]: > try: > post.tags.get(name__exact=tag) > posts[post.id] = post > except: > posts[post.id] = None > results = [post for post in posts.values() if post != None] > if len(results) == 0: > raise Http404 > else: > return render_to_response("blog/tags.html", { > 'posts': results, > }) > > This works. My question is just if there's a better way to accomplish > this. I realize that it'd be a lot cleaner if I just used hierarchical > categories. However, I'd like to keep this as flexible as possible by > using simple tags. This could be very much simplified now, and with the regex I mentioned above, the view would turn into something like: def tags(request, url): # Don't need the last item in the list since it will # always be an empty string since Django will append # a slash character to the end of URLs by default. tags = url.split('/')[:-1] posts = Post.objects.filter(tags__name__in=tags) return render_to_response("blog/tags.html", {'posts': posts}) --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~----------~----~----~----~------~----~------~--~---