Error with url when listing products from index.html file

1

I am trying to list products in a index.html file, I would greatly appreciate your help.

I have this file from the app url:

from django.conf.urls import url
from . import views

urlpatterns = [
 url(r'^$', views.hello_world, name='hello'),
 url(r'^product/(?P<pk>[0-9]+)/$', views.product_detail)
]

I'm trying to access this method found in the file views.py :

from django.http import HttpResponse
from django.template import loader
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)
    template = loader.get_template('product_detail.html')
    context = {
    'product': product
    }

    return HttpResponse(template.render(context,request))

and this is the file index.html where the products are ready and it shows an error in the browser when executing the application:

<!DOCTYPE html>
<html lang="en">
 <head>
     {% load staticfiles %}
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-
          scale=1">
     <link rel="stylesheet" href="{% static 'css/base.css' %}">
 </head>
 <body>
    <h1>Hola</h1>
    <ul>
        {% for pr in product %}
            <li>
                <a href="{% url 'products.views.product_detail' 
                    pk=pr.pk %}">
                    {{pr.name}}    
                </a>
                {{pr.description}}
                <img src="{{pr.image.url}}" alt="">               
            </li>
        {% endfor %}
    </ul>
  </body>
</html>

This is the error:

    
asked by Jhoan Lopez 02.09.2017 в 04:27
source

1 answer

1
{% for pr in product %}
    <li>
        <a href="{% url 'products.views.product_detail' pk=pr.pk %}">
            {{pr.name}}    
        </a>
        {{pr.description}}
        <img src="{{pr.image.url}}" alt="">               
    </li>
{% endfor %}

Let's start with the for, this is not the main problem but you can not iterate a single object, when you do the get_object_or_404 you are asking for a single object and not for several to perform the for, what you can do is an if, for see if we receive the product. Use product.name , product.description , ...

Now if the error is in <a href="{% url 'products.views.product_detail' pk=pr.pk %}"> it should be < a href="{% url 'products' pk=pr.pk %}"> . The reason? When we use the parametron {% url '' %} , we are asking for the name that we assign in the file urls.p and not the function.

from django.conf.urls import url
from . import views

#app_name='tu_nombre' #Si esto es una app agregale nombre para que la diferencie de las otras app y agregalo en la url de esta manera 'tu_nombre:products'

urlpatterns = [
 url(r'^$', views.hello_world, name='hello'),
 url(r'^product/(?P<pk>[0-9]+)/$', views.product_detail, name='products')
]
    
answered by 02.09.2017 / 23:27
source