模型中的Django变量不在模板中输出值

时间:2015-04-15 00:51:07

标签: python django

变量{{post}}在我的主页中给出了一个值,并且还允许我重定向到具有正确ID的帖子页面;但是,重定向到的页面不会显示{{post}}的任何值。我不确定问题是什么,我试图改变很多事情,我似乎无法找到问题所在。如何让变量{{post}}在其他页面上提供输出?

这是我的index.html和文章页面:

{% if news_posts %}
<div class="row">
    <div class="large-8 small-12 large-centered column" id="articles">
        <ul class="article_posts">
            {% for post in news_posts %}
                <li id="article_title"><a href="{% url 'articles:post' post.id %}">{{ post.post_title }}</a></li>
                <li id="article_date">Posted {{ post.post_date|timesince }} ago</li>
                <div id="arrow"></div>
                <hr>
                <li id="article_image"><img src="static/media/{{ post.post_image }}" /></li>
                <li id="article_shortdesc">{{ post.post_short_description }}</br><a href="{% url 'articles:post' post.id %}">Read More>>></a></li>
                <hr>
            {% endfor %}
        </ul>   
    </div>
</div>
{% endif %}

文章模板页面:

<div class="row">
    <div class="large-8 small-12 large-centered column" id="articles">
        <ul class="article_posts">
                <li id="article_title">{{ post.post_title }}</li>
                <li id="article_date">{{ post.post_date }}</li>
                <hr>
                <li id="article_image"><img src="static/media/{{ post.post_image }}" /></li>
                <li id="article_shortdesc">{{ post.post }}</li>
                <hr>
        </ul>   
    </div>
</div>

views.py

from django.shortcuts import render, render_to_response
from articles.models import newspost
from django.views import generic
from articles.forms import RequestEditor
from django.core.context_processors import csrf

class PostList(generic.ListView):
    template_name = 'articles/index.html'
    context_object_name = "news_posts"
    paginate_by = 5

    def get_queryset(self):
        return newspost.objects.order_by('-post_date')[:5]

class PostDetail(generic.DetailView):
    model = newspost
    template_name = 'articles/articles.html'

应用urls.py

from django.conf.urls import patterns, include, url

from articles import views

urlpatterns = patterns('',

    url(r'^$', views.PostList.as_view(), name='index'),
    url(r'^(?P<pk>\d+)/$', views.PostDetail.as_view(), name='post'),
    url(r'^editors_request_form/$', views.EditorsRequestForm, name='editors'),
)

项目urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    # Examples:
    # url(r'^blog/', include('blog.urls')),

    url(r'^', include('articles.urls', namespace="articles")),
    url(r'^editor_login/', include(admin.site.urls)),
)

1 个答案:

答案 0 :(得分:2)

您需要在context_object_name='post'中添加PostDetailView,否则使用的默认模板变量名称为object