Django 2.0中的QuerySet。不起作用

问题描述 投票:0回答:2

我在Django有一点休息,今天我决定回到这个框架。但是现在我对小学思考有一个问题。我想用波兰语完成一本指南。我已经安装了Django 2.0,我创建了一些像这样的东西:

models.朋友

    from django.db import models
from django.utils import timezone

class Post(models.Model):
    author = models.ForeignKey('auth.User',
    on_delete=models.CASCADE,
    )
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
        default=timezone.now
    )
    published_date = models.DateTimeField(
        blank = True, null = True
    )

    def publish(self):
        self.published_date = timezone.now()
        self.save

    def __str__(self):
        return self.title

项目urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'', include('blogs.urls')),
]

app urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.post_list, name='post_list'),]

views.朋友

from django.shortcuts import render
from django.utils import timezone
from .models import Post

def post_list(request):
    posts = Post.objects.order_by('title','published_date').first()
    return render(request, 'blogs/post_list.html', {})

和post_list.html

<div>
    <h1><a href="/">My blog</a></h1>
</div>

    {% for post in posts %}
        <div>
            <p>published: {{ post.published_date }}</p>
            <h1><a href="">{{ post.title }}</a></h1>
            <p>{{ post.text|linebreaksbr }}</p>
        </div>
    {% endfor %}

提示不会收到任何错误,但当我检查localhost:8000我只有一个<h1>文本。我尝试了很多解决方案,但仍然没有。我不知道为什么%for%中的QuerySet不起作用。有解决方案吗从Django 1.10到2.0有什么变化吗?

python django
2个回答
1
投票

在views.py中添加,

from django.shortcuts import render
from django.utils import timezone
from .models import Post

def post_list(request):
    #Remove .first() as it only returns one object
    posts = Post.objects.order_by('title','published_date')
    #You have to create a dictionary and pass it to render
    context = {
                 "posts" : posts ,
              }
    return render(request, 'blogs/post_list.html', context=context)

0
投票

queryset方法first()返回单个对象,顺序中的第一个对象。你不能迭代一件事,但你试图在你的模板中做到这一点。删除first()并发送所有对象,或删除模板中的for循环,然后输出单个对象本身。

© www.soinside.com 2019 - 2024. All rights reserved.