问题
Im trying to create pages for tags on my django blog. I already have a simple index page which displays a list of all used tags, now I want to have individual pages for each tag and on that page I will display all posts marked with that tag. The url structure for these tag detail pages will be like this
localhost/tag/my-tag-here
I already have django-taggit installed and added some tags and I have them displaying fine on post detail pages and the tag index page mentioned above but Im getting a 404 when I try to visit each tag detail page such as /tag/test.
These are my files and the full error message below.
views.py
def tag_detail(request, tag):
tag = get_object_or_404(Tag, tag=tag.name)
return render(request, 'blog/tags_detail.html', {'tag': tag})
urls.py (app)
urlpatterns = [
url(r'^$', views.blog_index, name='blog_index'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\
r'(?P<post>[-\w]+)/$',
views.blog_post_detail,
name='blog_post_detail'),
url(r'^contact/$', views.contact_form, name='contact_form'),
url(r'^thanks/$', views.thanks_view, name='thanks_view' ),
url(r'^about/$', views.about, name='about'),
url(r'^upload/$', views.upload_image, name='upload_image'),
url(r'^tag/(?P<tag>[-/w]+)/$', views.tag_detail, name='tag_detail'),
url(r'^tags/$', views.tags_index, name='tags_index')
]
and this is the full error message
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/tag/test
is the problem here in my view or the url structure? For the view I'm not 100% sure if thats the correct way to do it but Ive tried to do it the same as my post detail view.
thanks
回答1:
The problem is in your views.py file. In this code:
def tag_detail(request, tag):
tag = get_object_or_404(Tag, tag=tag.name)
return render(request, 'blog/tags_detail.html', {'tag': tag})
Here you wrote :
tag = get_object_or_404(Tag, tag=tag.name)
you passed a tag in URL so correct method would be :
tag = get_object_or_404(Tag, tag=tag)
But this will work only if, in your model,you have returned name of the tag as Unicode,Like this:
class Tag(models.Model):
name = models.CharField()
def __unicode__(self):
return unicode(self.name)
And if this still does not work then there might be a problem in TEPLATE_DIR setting in settings.py file. Then you have to share settings.py code for project file structure.
来源:https://stackoverflow.com/questions/40371598/tag-detail-page-with-django-taggit