0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

DjangoでListViewがtemplateに読み込まれないときの対処法

Last updated at Posted at 2019-10-25

環境

MacOS Mojave 10.14
Python 3.7.3
Django 2.2

現象

ListViewを書いたものの、自身の環境では何故か動かなく、どこかに異常があるのかと思って新しく環境を作ってソースコードをコピペしてみたら普通に動いた

原因

まずはソースコード

models.py

from django.db import models

class Category(models.Model):
    class Meta:
        # カテゴリ
        verbose_name = "Category"
        verbose_name_plural = "Category"

    # カラム名の定義
    category_name = models.CharField(max_length=255, unique=True)

    def __str__(self):
        return self.category_name


class Menu(models.Model):
    class Meta:
        verbose_name = "Menu"
        verbose_name_plural = "Menu"

    # カラムの定義
    name = models.CharField(verbose_name="Name", max_length=100)
    category = models.ForeignKey(Category, on_delete=models.PROTECT, verbose_name="Category")
    calorie = models.IntegerField(verbose_name="Carolie", help_text="kcal")
    protein = models.FloatField(verbose_name="Protein", help_text="g")
    fat = models.FloatField(verbose_name="Fat", help_text="g")
    carbohydrate = models.FloatField(verbose_name="Carbohydrate", help_text="g")

    def __str__(self):
        return self.name


views.py
from django.views.generic import ListView
from .models import Menu


# Create your views here.

class MenuIndexView(ListView):
    model = Menu
    paginate_by = 10
urls.py
from django.urls import path
from .views import MenuIndexView

app_name = 'foodlist'


urlpatterns = [
   path('', MenuIndexView.as_view())
]

menu_list.html

<table id="container" width="100%" class="container">
       <!-- 表の列の定義-->
      <thead>
      <tr>
        <th class="text-center">名前</th>
        <th class="text-center">カテゴリー</th>
        <th class="text-center">カロリー</th>
        <th class="text-center">タンパク質</th>
        <th class="text-center">脂質</th>
        <th class="text-center">炭水化物</th>
      </tr>
      </thead>
       <!-- ここまでが表の列の定義-->

       <!-- 表のデータ部分の表示-->
      <tbody>
      <tr>
        {% for menu in object_list %}
        <td class="text-center" width="100">{{ menu.name}}</td>
          <td class="text-center" width="100">{{ menu.category }}</td>
        <td class="text-center" width="140">{{ menu.carolie }}</td>
        <td class="text-center" width="140">{{ menu.protein }}</td>
        <td class="text-center" width="140">{{ menu.fat}}</td>
        <td class="text-center" width="140">{{ menu.carbohydrate }}</td>
          {% endfor %}
      </tr>

      </tbody>
       <!-- ここまでが表のデータ部分の表示-->
</table>
<!-- ここまでがテーブル表の定義 -->

これで一旦DBにテストのデータを入れてみるも一向に動かない。
書き方は間違ってはいないはずだと思い新しく環境を作って同じコードを試してみると動く。

原因がどこかにあるはずだと思いurls.pyをいじって起動時に呼び出される場所を変えてみたら上手く読み込まれる事が発覚。

そしてこの記事を読んで
Djangoにおけるクラスベース汎用ビューの入門と使い方サンプル
そもそもurls.pyの書き方が誤っていることに気がつく

(修正前)

urls.py
from django.urls import path
from .views import MenuIndexView

app_name = 'foodlist'


urlpatterns = [
   path('', MenuIndexView.as_view(),name="datatable")
]

(修正後) 修正(10/29) こちらの例はDjango1.x時代の書き方であり、Django2.xの現在の書き方にはそぐわない物でした。
ご指摘いただきありがとうございます。

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

app_name = 'foodlist'


urlpatterns = [
    url(r'^menu_list$', MenuIndexView.as_view(),name="datatable")
]

(真・修正後)

urls.py
from django.urls import path
from .views import MenuIndexView

app_name = 'foodlist'


urlpatterns = [
    path('menu_list', MenuIndexView.as_view(),name="datatable")
]

総評

ListViewのpathを名前指定せずにほったらかしておくと当然のことながらListViewは読み込まれませんでした。
修正後には無事読み込まれたのでとても良い勉強になりました。

基本的なところですがハマるとわからなくなったので、紹介した記事を読んでDjangoのformについての理解を深めたいと思います。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?