我正在尝试关注Simple Blog tutorial at Django By Example。我已经设法生成一个正确加载的网站,但是当索引视图加载查找,并且各个帖子的链接显示并且看起来格式正确时,它们指向索引模板,所以所有单击它们时发生的是它重新加载索引视图。我是Django的新手,教程很少,至少可以说是因为它是为旧版本的Django编写的,而我使用的是1.5。我整个下午一直在盯着它,我很迷茫。
这是我的urls.py
from django.conf.urls import patterns, url
from blog import views
urlpatterns = patterns('blog.views',
#index
(r"$", 'main'),
#ex: /1/
(r"^(\d+)/$", 'post'),
#ex: /add_comment/1/
(r"^add_comment/(\d+)/$", 'add_comment'),
)
my views.py
from blog.models import Post, PostAdmin, Comment, CommentAdmin
class CommentForm(ModelForm):
class Meta:
model = Comment
exclude = ["post"]
def main (request):
"""Main Listing."""
posts = Post.objects.all().order_by("-created")
paginator = Paginator(posts, 10)
try: page = int(request.GET.get("page", '1'))
except ValueError: page = 1
try:
posts = paginator.page(page)
except (InvalidPage, EmptyPage):
posts = patinator.page(paginator.num_pages)
return render_to_response("blog/list.html", dict(posts=posts, user=request.user))
def post (request, pk):
"""single post with comments and comment form"""
post = Post.objects.get(pk=int(pk))
comments = Comment.objects.filter(post=post)
d = dict(post=post, comments=comments, form=CommentForm(), user=request.user)
d.update(csrf(request))
return render_to_response("blog/post.html", d)
以及包含不在任何地方的链接的list.html!
{% extends "blog/bbase.html" %}
{% block content %}
<div class="main">
<!-- Posts -->
<ul>
{% for post in posts.object_list %}
<div class="title">{{ post.title }}</div>
<ul>
<div class="time">{{ post.created }}</div>
<div class="body">{{ post.body|linebreaks }}</div>
<div class="commentlink"><a href="{% url 'blog.views.post' post.pk %}">Comments</a></div>
</ul>
{% endfor %}
</ul>
<!-- Next/Prev page links -->
{% if posts.object_list and posts.paginator.num_pages > 1 %}
<div class="pagination" style="margin-top: 20px; margin-left: -20px; ">
<span class="step-links">
{% if posts.has_previous %}
<a href= "?page={{ posts.previous_page_number }}">newer entries << </a>
{% endif %}
<span class="current">
Page {{ posts.number }} of {{ posts.paginator.num_pages }}
</span>
{% if posts.has_next %}
<a href="?page={{ posts.next_page_number }}"> >> older entries</a>
{% endif %}
</span>
</div>
{% endif %}
</div>
{% endblock %}
答案 0 :(得分:1)
Django URL解析器将返回与传入请求匹配的第一个URL模式。 “主要”视图r"$"
的正则表达式将匹配任何传入请求,因为您只查找字符串结尾的$
。
您需要将“主”网址正则表达式更改为r'^$'
。
或者,如果您想要一个全能视图,可以将“主要”视图移动到您的网址底部