2017-04-09 7 views
1

みなさん、こんにちは! 私はちょうどジャンゴプログラミングの方法を開始するので、時には本当に混乱することがあります。Django objects.all()はコンテンツを表示しません

私はすべてのオブジェクトをDBから表示しようとしていますが、ページを開くとそのオブジェクトは単に空です。

コンテンツが追加されていて、以前ListViewを試してみましたが、それは私のために働いていました。しかし、今私はグリッドのようなオブジェクトをdislpayする必要があり、ここでこのメソッドの問題です。

ご協力いただきありがとうございます。

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 %} 

ところで、どのようにその可能な、グリッドのようなあなたのオブジェクトを表示リストではないので、上のブートストラップまたはを使用します。

ありがとうございました!

答えて

2

あなたのテンプレートにall_postsという名前のものを反復しています。しかし、あなたの意見はall_postsと呼ばれるものを送信しません。 postsのみを送信します。一貫した名前を使用する必要があります。

+0

ohhh ... ListViewの変数だったので、私はとても礼儀正しく、友人に感謝します!グリッドではなくグリッドのように見えるようにオブジェクトを実装する方法はありますか? – Michael

+0

グリッドで何を意味するのかよく分かりませんが、必要に応じてHTMLでテーブルタグを使用できます。 –

+0

私は、1つの行にいくつかのオブジェクトを動的に表示する必要があることを意味します。現在、私のテンプレートでは、リストのように順番に1つずつ進んでいます。 – Michael

関連する問題