Post List and Detail View in Django: E-Commerce Website Using Django, Episode 7.

Started by ygg97no6y7, Oct 21, 2024, 05:53 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.


fomlufamli

�In Episode 7 of the "E-Commerce Website Using Django" series, titled "Post List and Detail View in Django", the tutorial focuses on implementing two essential views for an e-commerce site: the product list view and the product detail view.�

🛍� Product List View
The product list view displays all available products on the homepage. It retrieves all product entries from the database and renders them in a template.�

views.py:

python
Copy
Edit
from django.shortcuts import render
from .models import Product

def product_list(request):
    products = Product.objects.all()
    return render(request, 'product_list.html', {'products': products})
product_list.html:

html
Copy
Edit
{% for product in products %}
    <div class="product">
        <h2>{{ product.name }}</h2>
        <p>{{ product.description }}</p>
        <p>${{ product.price }}</p>
        <a href="{% url 'product_detail' product.id %}">View Details</a>
    </div>
{% endfor %}
Stack Overflow
+2
GeeksforGeeks
+2
YouTube
+2

🛒 Product Detail View
The product detail view displays detailed information about a single product when a user clicks on a product from the list.�

views.py:

python
Copy
Edit
from django.shortcuts import render, get_object_or_404
from .models import Product

def product_detail(request, pk):
    product = get_object_or_404(Product, pk=pk)
    return render(request, 'product_detail.html', {'product': product})
product_detail.html:

html
Copy
Edit
<h1>{{ product.name }}</h1>
<p>{{ product.description }}</p>
<p>${{ product.price }}</p>
<img src="{{ product.image.url }}" alt="{{ product.name }}">
<a href="{% url 'product_list' %}">Back to Products</a>
🔗 URL Configuration
Ensure that the URLs for these views are properly configured in your urls.py.�
GeeksforGeeks

python
Copy
Edit
from django.urls import path
from . import views

urlpatterns = [
    path('', views.product_list, name='product_list'),
    path('product/<int:pk>/', views.product_detail, name='product_detail'),
]
For a more in-depth walkthrough, you can watch the full tutorial here:

Didn't find what you were looking for? Search Below