使用Listview类django 2在模板中访问对象详细信息

时间:2017-12-14 11:04:29

标签: python django django-2.0

我正在关注一个教程,我想在我的模板html文件中显示每个对象属性(保存在db中),如下所示:

{% for obj in objects_list %}
    <p>{{ obj.name }} => {{ obj.location }} <b>timecreated</b>==> {{ obj.timestamp }} <b>time updated</b>==> {{ obj.updated }}</p>

{% endfor %}

我应该知道url和这个网址

http://localhost:8000/restaurants/shomal/

/shomal/是我们的slug,我们必须观察类别等于= shomal的对象细节

我无法在模板中看到循环结果,但在打印查询集中我可以看到终端中的对象详细信息

为什么我无法在循环模板中找到对象详细信息?

在我的应用视图文件中,我有

from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.views import View
from django.views.generic import TemplateView, ListView
from .models import Restaurant
from django.db.models import Q


def restaurants_listview(request,):
    template_name = 'restaurants/restaurants_list.html'
    query_set = Restaurant.objects.all()
    context = {
        "objects_list": query_set
    }
    return render(request, template_name, context)


class RestaurantListView(ListView):
    template_name = 'restaurants/restaurants_list.html'

    def get_queryset(self):
        print(self.kwargs)
        slug = self.kwargs.get("slug")
        if slug:
            queryset = Restaurant.objects.filter(
                Q(category__iexact=slug)|
                Q(category__icontains=slug)
            )
            print(queryset)

        # return queryset
        else:
            queryset = Restaurant.objects.all()
        return queryset

在django url.py文件中我有

from django.contrib import admin
from django.urls import path
from django.views.generic.base import TemplateView
from restaurants.views import (
    restaurants_listview,
    RestaurantListView
)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', TemplateView.as_view(template_name="home.html")),
    path('restaurants/', RestaurantListView.as_view()),
    path('restaurants/<str:slug>/', RestaurantListView.as_view()),
    path('about/', TemplateView.as_view(template_name="about.html")),
    path('contact/', TemplateView.as_view(template_name="contact.html")),
]

这是我的模型文件

from django.db import models


# Create your models here.
class Restaurant(models.Model):

    name = models.CharField(max_length=120)
    location = models.CharField(max_length=120, null=True, blank=True)
    category = models.CharField(max_length=120, null=True, blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

1 个答案:

答案 0 :(得分:2)

默认情况下,ListView将对象列表添加到模板上下文object_list。您目前有objects_list

最简单的解决方法是将模板更改为使用object_list

{% for obj in object_list %}
    <p>{{ obj.name }}</p>
{% endfor %}

由于您的模型为Restaurant,您还可以使用restaurant_list,这会使您的模板更具描述性:

{% for restaurant in restaurant_list %}
    <p>{{ restaurant.name }}</p>
{% endfor %}

如果您不想使用object_listrestaurant_list,则另一个选项是设置context_object_name