我花了好几个小时做这件事。
我有一个类别页面,如果我点击一个特定的页面,那么该页面内的帖子列表会导致单个帖子页面。
单个帖子页面正常工作,单个类别页面正常工作,但是类别页面内的页面无效,这有意义吗?
def post(request, slug):#this is my view
single_post = get_object_or_404(Post, slug=slug)
single_post.views += 1 # increment the number of views
single_post.save() # and save it
t = loader.get_template('main/post.html')
context_dict = {
'single_post': single_post,
}
c = Context(context_dict)
return HttpResponse(t.render(c))
def category(request, category_name_slug):
context_dict = {}
try:
category = Category.objects.get(slug=category_name_slug)
context_dict['category_name'] = category.name
posts = Post.objects.filter(category=category)
context_dict['posts'] = posts
context_dict['category'] = category
except Category.DoesNotExist:
pass
return render(request, 'main/category.html', context_dict)
this is my url
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<slug>[\w|\-]+)/$', views.post, name='post'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category')
]
这是我的类别html
{% extends 'base.html' %}
{% block content %}
<h1>{{category_name}}</h1>
{% if category %}
{%if posts %}
<ul>
{% for post in posts %}
<h3><a href="{{ post.slug }}">{{ post.title }}</a></h3>
{% endfor %}
</ul>
{%else%}
<strong>No Pages </strong>
{% endif %}
{% else %}
{{category_name}} does not exist
{% endif %}
{% endblock %}
最后post.html
<html>
<head>
<title></title>
<head>
<body>
<h2>{{single_post.title}}</h2>
<p>{{single_post.content}}</p>
<p> Views: {{single_post.views}}
<br>
<p>
{% if single_post.image %}
<img src="/media/{{single_post.image}}">
{% endif %}
</p>
<body>
它给了我404错误,有趣的是url给我的错误是127.0.0.1:8000/category/hello/adele但127.0.0.1:8000/adele不给我错误。所以在类别页面内,我想访问127.0.0.1:8000/adele -
答案 0 :(得分:1)
将<a href="{{ post.slug }}">{{ post.title }}</a>
替换为<a href="/{{ post.slug }}">{{ post.title }}</a>
问题是如果锚中的引用不是以/
开头,则表示它是一个相对URL,并且该引用被添加到当前url。希望这对你有所帮助。如需进一步参考,请使用django的absolute_url功能。请阅读this:)
答案 1 :(得分:0)
使用url模板标记:
convert_0_1_2 :: State (a, b) x -> State (a, b, c) x
convert_0_1_2 f = do
(a, b, c) <- get
let (x, (a', b')) = runState f (a, b)
put (a', b', c)
return x
convert_0_2_1_0 :: State (c, b) x -> State (a, b, c, d) x
convert_0_2_1_0 f = do
(a, b, c, d) <- get
let (x, (b', c')) = runState f (b, c)
put (a, b', c', d)
return x
根据您的网址配置重建网址,确保它是有效的网址。这里,{% for post in posts %}
<h3><a href="{% url 'post' slug=post.slug %}">{{ post.title }}</a></h3>
{% endfor %}
是您在urlconf中定义的网址的名称,'post'
是您传递给网址正则表达式中的捕获组的参数。