大家好! 我刚刚开始 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/