Django基于类的ListView与基于函数的list_view

时间:2018-08-23 13:55:32

标签: django django-views django-class-based-views

因此,我正在努力解决以下问题。 customer_list的基于类的视图就像一个超级按钮一样工作,它显示了位于客户表中的所有客户的列表。但是,应该执行完全相同的基于函数的视图将返回空。

也许我缺少一些东西,但我只想知道两种视图之间的差异以及何时使用。

如果有人可以解释我所缺少的内容?

urls.py

from django.conf.urls import url, include
from . import views

# Function based view
url(r'^all_customers/$', views.customer_list, name='all_customers'),

# Class based view
url(r'^all_customers/$', views.customer_list.as_view(),name='all_customers'),

views.py

from django.views import generic
from django.shortcuts import render
from .models import Customer

# Function based view
def customer_list(request):
    customers = Customer.objects.all()
    return render(request, 'all_customers.html', {'customers': customers})

# Class based view
class CustomerList(generic.ListView):
    model = Customer
    template_name = 'all_customers.html'

models.py

from django.db import models

class Customer(models.Model):
    first_name = models.CharField(max_length=200)
    prefix = models.CharField(max_length=8, null=True, blank=True)
    last_name = models.CharField(max_length=200)

这是模板的一部分

{% for customer in customer_list %}
<tr>
    <td>{{customer.pk}}</td>
    <td>
    {% if customer.prefix %}
        {{customer.first_name}}  {{customer.prefix}}  {{customer.last_name}}
    {% else %}
        {{customer.first_name}}  {{customer.last_name}}
    {% endif %}
    </td>
</tr>
{% endfor %}

1 个答案:

答案 0 :(得分:0)

您在urls.py中导入错误 您应该使用.views import customer_list