如何使用 ListView 正确显示 Django 表单

How do I display a Django form correctly using ListView

我正在编写一个简单的应用程序来根据 Django 教程“编写您的第一个 Django 应用程序”(https://docs.djangoproject.com/en/4.0/intro/tutorial01/) 跟踪销售线索。除了显示现有潜在客户的 ListView 之外,一切都很好。

以下是相关的 python 片段:

Leads/models.py

class Leads(models.Model):
    id = models.IntegerField(primary_key=True)
    last = models.CharField(max_length=32)
    first = models.CharField(max_length=32)

config/urls.py

urlpatterns = [
    # Django admin
    path('admin/', admin.site.urls),

    # User management
    path('accounts/', include('allauth.urls')),

    # Local apps
    path('leads/', include('leads.urls')) 

leads/urls.py

app_name = 'leads'

urlpatterns = [
    path('', LeadsListView.as_view(), name='list'),
    path('<int:pk>/', LeadsDetailView.as_view(), name='detail'),
]

leads/views.py

class LeadsListView(ListView):
    model = Leads
    template_name = 'leads/list.html'
    context_object_name = 'leads_list'
    def get_queryset(self):
        return Leads.objects.order_by('id')

class LeadsDetailView(DetailView):
    model = Leads
    template_name = 'leads/detail.html'

'home.html'模板中的link,正确显示菜单选项:

<a href="{% url 'leads:list' %}">Leads</a>

最后,'list.html' 模板根本不显示。它没有显示潜在客户列表,而是保留在主页上。

{% block content %}
{% for lead in lead_list %}
<div class="lead-entry">
    <h2><a href="{% url 'leads:detail' lead.pk %}">{{ lead.fname }} {{ lead.lname }}</a></h2>
</div>
{% endfor %}
{% endblock content %}

我在这里遗漏了一些基本的东西....

有一些小错误,例如:

问题

  1. context_object_name='leads_list,而你在模板文件中定义为lead_list,错过了s

  2. 您的模型字段名称是 firstlast,而不是 fnamelname

解决方案:

在您的模板中试试这个:

{% block content %}
{% for lead in leads_list %}
<div class="lead-entry">
    <h2><a href="{% url 'leads:detail' lead.pk %}">{{ lead.first }} {{ lead.last }}</a></h2>
</div>
{% endfor %}
{% endblock content %}

我把lead.fname改成了lead.first,把lead.lname改成了lead.last,还把s改成了lead_list,现在是leads_list.

Note: Models in django doesn't require its name in plural form, it would be better if you only give name model name Lead rather than Leads, as django itself adds s as the suffix.

Note: If you are overriding the default AutoField generated by django which is id, so you must override it with AutoField[django-doc] rather than making IntegerField primary key.