python - Django objects.all() 不显示任何内容

标签 python django python-3.x django-models django-views

大家好! 我刚刚开始 django 编程,所以有时真的很困惑。

我试图显示数据库中的所有对象,但打开页面时它只是空的。

添加了内容,我之前尝试过 ListView,它对我有用。但现在我需要显示网格等对象,这是此方法的一个问题。

非常感谢您的帮助!

models.py

from django.db import models


class Post(models.Model):
    title = models.CharField(max_length=140)
    body = models.TextField()
    date = models.DateField()
    image = models.ImageField(upload_to='bons_images/%Y/%m/%d')

    def __str__(self):
        return self.title

views.py

from django.shortcuts import render, render_to_response
from django.template import RequestContext
from django.views import generic

from blog.models import Post


def image(request):
    post = Post()
    variables = RequestContext(request, {
        'post': post
    })
    return render_to_response('blog/post.html', variables)


# class IndexView(generic.ListView):
#     template_name = 'blog/blog.html'
#     context_object_name = 'all_posts'
#
#     def get_queryset(self):
#         return Post.objects.all()

def index(request):
    posts = Post.objects.all()
    return render(request, 'blog/blog.html', {'posts': posts})

urls.py

from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post
from blog import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^(?P<pk>\d+)$', DetailView.as_view(model=Post, template_name='blog/post.html')),
]

blog.html

{% extends 'base.html' %}

{% block content %}

    {% if all_posts %}
        {% for post in all_posts %}
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-3 col-lg-4">
                        <div class="thumbnail">
                            <a href="/blog/{{ post.id }}">
                                <h5>{{ post.date|date:'Y-m-d' }} {{ post.title }}</h5>
                                <img src="{{ post.image.url }}" style="width: 50%; height: 50%"/>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        {% endfor %}
    {% endif %}
{% endblock %}

顺便说一下,如何使用 Bootstrap 等在网格中而不是列表中显示对象。

谢谢!

最佳答案

您正在迭代模板中名为 all_posts 的内容。但是您的 View 不会发送任何名为 all_posts 的内容;它只发送帖子。您需要使用一致的名称。

关于python - Django objects.all() 不显示任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43312278/

相关文章:

python - EEG 数据的频率电压图 - Python 中的 FFT

python - 想要使用 python swiftclient 将 sqlite.db 文件上传到 swift 容器并且总是得到 utf-8 错误

带有 numpy 的 Django,错误 :cannot import name multiarray

algorithm - 为什么我不能遍历数据框中的新列?

python - 以时间间隔连续安排脚本

python - 在 DLL 中嵌入 Python : Access violation reading location when Py_DECREF list object

Python 正则表达式匹配上一组中的匹配项(多选 1)

python - 修改后代中的祖先嵌套元类

websocket 启动时的 django channel 错误消息 (Sessions.py)

python-3.x - 检查 py 文件是否由 ide 或命令行运行