1

我正在 Django 中制作一个简单的博客应用程序作为学习练习。我可以添加帖子,在首页上看到它们,所以到目前为止它正在工作。我遇到的问题是创建一个在单独的页面上显示整个帖子的视图。我想单击标题,然后转到具有标题和正文的 url /post/primary 键的页面。当我点击链接时,我得到一个只有 base.html 的页面。不知道我在哪里遗漏了任何东西,这里是 urls.py、views.py 和 post.html:

来自 django.conf.urls 的 urls.py 导入模式、包含、url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('blog.views',
    url(r'^$', 'frontpage'),
    url(r'^post/(\d+)/$', 'post'),
)

urlpatterns += patterns('',
    url(r'^admin/', include(admin.site.urls)),
) 

from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, render_to_response
from blog.models import *

视图.py

def frontpage(request):
    posts = Post.objects.all().order_by("-created")
    paginator = Paginator(posts, 5)

    page = request.GET.get('page', '1')

    try: 
        posts = paginator.page(page)
    except (InvalidPage, EmptyPage):
        posts = paginator.page(paginator.num_pages)

    return render_to_response("list.html", dict(posts=posts, user=request.user))

def post(request, pk):
    """Single Post"""
    post = Post.objects.get(pk = pk)
    d = dict(post=post, user=request.user)
    return render_to_response("post.html", d)

post.html

{% extends "base.html" %}

{% block content %}
    <div class ="main">
        <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>
                </ul>
            {% endfor %}
        </ul>
    </div>
{% endblock %}

在此先感谢您的帮助。

4

2 回答 2

1

我假设这page.html实际上是post.html您在 yoru 代码示例中拥有的?您不再拥有一系列帖子,而是只有 1 个帖子

这需要更改为:(循环浏览您的帖子)

{% extends "base.html" %}

{% block content %}
    <div class ="main">
        <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>
                </ul>
            {% endfor %}
        </ul>
    </div>
{% endblock %}

类似于(仅显示您的单曲post):

{% extends "base.html" %}

{% block content %}
    <div class ="main">
        {{ post.title }}
        {{ post.created }}
        {{ post.body }}      
    </div>
{% endblock %}
于 2012-12-13T17:14:44.220 回答
0

您必须更改 urls.py 才能转到 url /post/primary 键处的页面。

urlpatterns = 模式('blog.views',
    网址(r'^$','首页'),
    url(r'^post/(?P<pk>\d+)/$', 'post'),
)
于 2012-12-14T06:52:30.917 回答