Home > Software design >  How do I display a Django form correctly using ListView
How do I display a Django form correctly using ListView

Time:04-30

I am writing a simple app to track sales leads based on the Django tutorial "Writing your first Django app" (https://docs.djangoproject.com/en/4.0/intro/tutorial01/). Everything works well except for displaying a ListView of the existing leads.

Here are the relevant python snippets:

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'

The link in the 'home.html' template, which displays a menu option correctly:

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

And finally, the 'list.html' template that does not display at all. Instead of showing the list of leads, it remains on the home page.

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

I'm missing something fundamental here....

CodePudding user response:

There are some minor mistakes such as:

Issue

  1. The context_object_name='leads_list, and you have defined in your template file as lead_list, missed the s.

  2. Your Model field's name is first and last, not fname and lname.

Solution:

Try this out in your template:

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

I have changed lead.fname to lead.first and lead.lname to lead.last and also add s to lead_list, it is now 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.

  • Related