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 和这个 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
4

1 回答 1

3

默认情况下,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_listor restaurant_list,另一种选择是设置context_object_name.

于 2017-12-14T11:10:17.700 回答