'How do I display a Django form correctly using ListView
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 class="lead-entry">
<h2><a href="{% url 'leads:detail' lead.pk %}">{{ lead.fname }} {{ lead.lname }}</a></h2>
</div>
{% endfor %}
{% endblock content %}
I'm missing something fundamental here....
Solution 1:[1]
There are some minor mistakes such as:
Issue
The
context_object_name='leads_list, and you have defined in your template file aslead_list, missed thes.Your Model field's name is
firstandlast, notfnameandlname.
Solution:
Try this out in your template:
{% 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 %}
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 nameLeadrather thanLeads, as django itself addssas the suffix.
Note:If you are overriding the defaultAutoFieldgenerated by django which isid, so you must override it withAutoField[django-doc] rather than makingIntegerFieldprimary key.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
