Home > OS >  Django views are not rendering in template
Django views are not rendering in template

Time:11-13

Can someone tell me what I'm doing wrong here? The 1st function(all_products) renders in template perfectly, but the last 2 does not.

models.py

# TABLE BRAND
class Brand(models.Model):
    name = models.CharField(max_length = 50)

# TABLE PRODUCT
class Product(models.Model):
    title       = models.CharField(max_length = 100)
    brand       = models.ForeignKey(Brand, on_delete = models.CASCADE)
    image       = models.ImageField(null = False, blank = False, upload_to ="images/",)
    price       = models.DecimalField(max_digits = 100, decimal_places = 2, )
    created     = models.DateTimeField(auto_now_add = True )

the functions in the views.py

def all_products(request):
    products = Product.objects.all()
    return render(request, 'store/home.html', {'products': products})

def newest_products(request):
    sixNewestProduct = Product.objects.all().order_by('-created')[:6]
    return render(request, 'store/home.html', {'sixNewestProduct': sixNewestProduct})

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.all_products, name= 'all_products'), 
    path('', views.newest_products, name= 'newest_products'), 
    path('', views.newest_discount, name= 'newest_discount'), 
]

the template part look like this:

            {% for new in sixNewestProduct %}
            <a  href="#" >
                <div >
                    <img src="{{new.image.url}}" alt="">
                </div>
                <h5>{{new.brand.name}}</h5>
                <h4>{{new.title}}</h4>
                <p>{{new.price}} GNF</p>
            </a>
            {% endfor %}

CodePudding user response:

Need to correct url path like this

from django.urls import path
from . import views

urlpatterns = [
    path('', views.all_products, name= 'all_products'), 
    path('newest_products/', views.newest_products, name= 'newest_products'), 
    path('newest_discount/', views.newest_discount, name= 'newest_discount'), 
]

CodePudding user response:

Django matches the request with the first view it encounters which path matches the current request's path:

from django.urls import path
from . import views

urlpatterns = [
    # Django will always match this '' to the view `all_products`
    path('', views.all_products, name= 'all_products'), 
    path('', views.newest_products, name= 'newest_products'), 
    path('', views.newest_discount, name= 'newest_discount'), 
]

as @Mahammadhusain kadiwala answer, you'll have to add a different route path for each view

  • Related