另一個領域,而不是ID我使用Django 1.5的Django在網址中使用模板標籤
我有這個代碼塊在HTML文件
{% for p in latest_posts %}
<li><a href="{% url 'blog:detail' p.id %}">{{p.title}}</a></li>
{% endfor %}
如果我改變p.id到頁。標題
{% for p in latest_posts %}
<li><a href="{% url 'blog:detail' p.title %}">{{p.title}}</a></li>
{% endfor %}
然後我收到以下錯誤
Reverse for 'detail' with arguments '(u'Second post',)' and keyword arguments '{}' not found.
我希望url是/ title而不是/ id。
這是我的urls.py文件
urlpatterns = patterns ('',
url(r'^(?P<title>\w+)/$',
PostDetailView.as_view(),
name = 'detail'
),
)
我應該用get_absolute_url?
更新
我加了廢料場,但它仍然無法正常工作
{% url 'blog:detail' p.slug %}
我得到的錯誤是
Reverse for 'detail' with arguments '(u'third-post',)' and keyword arguments '{}' not found.
Post模型
class Post(models.Model):
title = models.CharField(max_length = 225)
body = models.TextField()
slug = models.SlugField()
pub_date = models.DateTimeField()
modified = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.title
管理員更新
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug" : ("title",)}
admin.site.register(Post, PostAdmin)
如果這個工程
<a href="{% url 'blog:detail' p.id %}">{{p.title}}</a>
爲什麼不這項工作
<li><a href="{% url 'blog:detail' p.slug %}">{{p.title}}</a></li>
更新
PostDetailVie w^
class PostDetailView(DetailView):
template_name = 'blogapp/post/detail.html'
def get_object(self):
return get_object_or_404(Post, slug__iexact = self.kwargs['slug'])
因此,您希望博客帖子的網址是'/ blog/second-post'而不是'/ blog/2'嗎? – Ngenator 2013-03-04 00:51:29
是的,我想要的網址是/博客/第二後 – iJK 2013-03-05 00:54:32