Displaying Contacts
Learn about Displaying Contacts
Creating the View
Open contacts/views.py and create a function-based view called contact_list. This view queries all Contact objects from the database using Contact.objects.all() and passes them into a template as context. The queryset is assigned to a variable called "contacts" so it can be accessed in the HTML template.
Setting Up URL Routing
Create a new file called contacts/urls.py. Define a URL pattern that maps the root path to the contact_list view. Then include this file in the main config/urls.py by adding a path that points to the contacts app URLs.
Creating the Base Template
Create a templates directory inside the contacts app. Inside it, create a base.html file that contains the common HTML structure shared by all pages — the doctype, html tag, head section with CSS links, and a body with a navbar. Add a block called "content" where child templates will inject their page-specific HTML. Include the HTMX script from a CDN in the head section.
Building the Contact List Template
Create a contact_list.html template that extends base.html. Inside the content block, loop through the contacts queryset using Django's template for loop. For each contact, display their name, email, and phone number inside a styled card or table row.
Handling Empty States
Use Django's empty tag inside the for loop to display a friendly message when no contacts exist yet. Something like "No contacts found. Add your first contact!" provides a much better user experience than showing an empty page.
Styling with Tailwind or DaisyUI
Add Tailwind CSS and DaisyUI via their CDN links in the base template. DaisyUI provides pre-built component classes like "card", "table", "btn", and "badge" that make your templates look polished with minimal effort.