开发者

Django custom tag no longer works

开发者 https://www.devze.com 2023-02-02 21:55 出处:网络
I made a custom tag to display a list of categories and its url which worked until I made a category detail view which will only display articles based on the category.

I made a custom tag to display a list of categories and its url which worked until I made a category detail view which will only display articles based on the category.

Here is the category view:

from blog.models import Category, Entry
from django.shortcuts import render_to_response, get_object_or_404
from django.views.generic import list_detail

#for template tag to display all categories
def all_categories(request):
 return render_to_response('category_detail.html', {
            'categories': Category.objects.all()
        })

def category_detail(request, slug):
 """
 object_list
  List of posts specific to the given category.
 category
  Given category.
 """
 return list_detail.object_list(
         request,
         queryset = Entry.objects.filter(categories = Category.objects.filter(slug = slug)),
   extra_context = {'category': Category.objects.filter(slug = slug)},
    template_name = 'blog/category_detail.html',
     )

Categories url:

from django.conf.urls.defaults import * 
from django.views.generic.list_detail import object_list, object_detail 
from blog.views.category import category_detail 
from blog.models import Category, Entry

# for category detail, include all entries that belong to the category
category_info = {
 'queryset' : Category.objects.all(), 
 'template_object_name' : 'category', 
 'extra_context' : { 'entry_list' : Entry.objects.all }
}

urlpatterns = patterns('', 
 url(r'^$', 'django.views.generic.list_detail.object_list', {'queryset': Category.objects.all() }, 'blog_category_list'),
 url(r'^(?P<slug>[-\w]+)/$', category_detail),
)

and 开发者_如何学Pythonthe custom category tag:

from django import template
from blog.models import Category

def do_all_categories(parser, token):
 return AllCategoriesNode()

class AllCategoriesNode(template.Node):
 def render(self, context):
  context['all_categories'] = Category.objects.all()
  return ''

register = template.Library()
register.tag('get_all_categories', do_all_categories)

Also here is how i am using the custom tag in base.html:

{% load blog_tags %}
<p>
 {% get_all_categories %}
 <ul>
 {% for cat in all_categories %}
  <li><a href="{{ cat.get_absolute_url }}">{{ cat.title }}</a></li>
 {% endfor %}
 </ul>
</p>

Before I added category_detail in the view, the custom tag would display the url correctly like: /categories/news. However, now all of the links from the custom tag just displays the url or the current page your on. Whats weird is that it displays the category name correctly.

Does anyone know how to get the urls to work again?

EDIT

here is my category model, maybe something is wrong with my get_absolute_url():

import datetime
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class Category(models.Model):
    title = models.CharField(max_length = 100)
    slug = models.SlugField(unique = True)

    class Meta:
        ordering = ['title']
        verbose_name_plural = "Categories"

    def __unicode__(self):
        return self.title 

    @models.permalink
    def get_absolute_url(self):
        return ('category_detail', (), {'slug': self.slug })

EDIT: updated get_absolute_url for Category model, however, that did not fix my problem. Also if i wasnt clear earlier, the category url worked even before changing the get_absolute_url


I am going to bet that get_absolute_url is actually returning an empty string. This would make the links reload the current page. Check out your HTML and look for something like this:

<a href="">Category Title Example</a>

If the URLs are actually blank, there is probably an error in get_absolute_url. When a Django template encounters an error when outputting a template variable it returns an empty string. Try calling get_absolute_url from a Django shell and see if it returns properly:

Category.objects.all()[0].get_absolute_url()

It looks like you renamed your view from blog_category_detail to category_detail, but forgot to update the reference in get_absolute_url.

Update: It doesn't look like the reverse URL lookup for 'category_detail' would succeed. Your urls file does not name the category_detail URL. You should either change the get_absolute_url reference to app_name.views.category_detail (or wherever it is stored) or name the URL by replacing that last line in your urls file with:

url(r'^(?P<slug>[-\w]+)/$', category_detail, name='category_detail'),

To find the source of the problem, you should debug this code from a command line. Something like this should do:

$ python manage.py shell
>>> from blog.mobels import Category
>>> cat = Category.objects.all()[0]
>>> cat.get_absolute_url()
0

精彩评论

暂无评论...
验证码 换一张
取 消