Django 自定义标签不再起作用
我制作了一个自定义标签来显示类别列表及其 url,直到我制作了一个类别详细信息视图(该视图仅显示基于该类别的文章)为止。
这是类别视图:
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',
)
类别 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),
)
和自定义类别标记:
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)
另外,这也是我在 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>
在视图中添加category_detail 之前,自定义标记将正确显示 url,如:/categories /消息。但是,现在自定义标签中的所有链接都只显示 URL 或当前页面。奇怪的是它正确显示了类别名称。
有谁知道如何让网址再次工作?
这里编辑
是我的类别模型,也许我的 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 })
编辑:更新了类别模型的 get_absolute_url,但是,这并没有解决我的问题。另外,如果我之前不清楚,类别 url 甚至在更改 get_absolute_url 之前就可以工作
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'^
and the 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
, 'django.views.generic.list_detail.object_list', {'queryset': Category.objects.all() }, 'blog_category_list'),
url(r'^(?P<slug>[-\w]+)/
and the custom category tag:
Also here is how i am using the custom tag in base.html:
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():
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
, category_detail),
)
and the custom category tag:
Also here is how i am using the custom tag in base.html:
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():
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我敢打赌
get_absolute_url
实际上返回一个空字符串。这将使链接重新加载当前页面。检查您的 HTML 并查找类似以下内容:如果 URL 实际上为空,则
get_absolute_url
中可能存在错误。当 Django 模板在输出模板变量时遇到错误时,它会返回一个空字符串。尝试从 Django shell 调用get_absolute_url
并查看它是否正确返回:看起来您将视图从
blog_category_detail
重命名为category_detail
,但忘记了更新get_absolute_url
中的引用。更新:
'category_detail'
的反向 URL 查找似乎不会成功。您的 urls 文件未命名category_detail
URL。您应该将get_absolute_url
引用更改为app_name.views.category_detail
(或存储它的任何位置),或者通过将 urls 文件中的最后一行替换为以下内容来命名 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: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 callingget_absolute_url
from a Django shell and see if it returns properly:It looks like you renamed your view from
blog_category_detail
tocategory_detail
, but forgot to update the reference inget_absolute_url
.Update: It doesn't look like the reverse URL lookup for
'category_detail'
would succeed. Your urls file does not name thecategory_detail
URL. You should either change theget_absolute_url
reference toapp_name.views.category_detail
(or wherever it is stored) or name the URL by replacing that last line in your urls file with:To find the source of the problem, you should debug this code from a command line. Something like this should do: