Django1.5を使用しています
私はhtmlファイルにこのコードのブロックを持っています
{% for p in latest_posts %}
<li><a href="{% url 'blog:detail' p.id %}">{{p.title}}</a></li>
{% endfor %}
p.idをp.titleに変更した場合
{% 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を/idではなく/titleにします。
これは私の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.
ポストモデル
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>
アップデート
PostDetailView
class PostDetailView(DetailView):
template_name = 'blogapp/post/detail.html'
def get_object(self):
return get_object_or_404(Post, slug__iexact = self.kwargs['slug'])