Reputation: 292
Good day.
So i'm going through Django 2 by Example and i've encoutered a strange error when visiting a object from list of objects.
TypeError at /1/black-tea/
product_detail() got an unexpected keyword argument 'id'
The type it recieves is correct so small help would be appriciated.
code from views.py
def product_detail(request, product_id, slug):
product = get_object_or_404(Product, slug=slug,
id=product_id, available=True)
return render(request, 'shop/product/detail.html',
{'product': product})
models.py
class Product(models.Model):
category = models.ForeignKey(Category,
related_name='products',
on_delete=models.CASCADE)
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d',
blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'))
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_detail',
args=[self.id, self.slug])
urls.py
path('<int:id>/<slug:slug>/', product_detail, name='product_detail'),
Code from template
<div id="main" class="product-list">
<h1>{% if category %} {{ category.name }}{% else %}Products{% endif %}</h1>
{% for product in products %}
<div class="item">
<a href="{{ product.get_absolute_url }}">
<img src="{% if product.image %}{{ product.image.url }}
{% else %}{% static 'img/images.jpeg' %}{% endif %}">
</a>
<a href="{{ product.get_absolute_url }}">{{ product.name }}</a>
<br>
${{ product.price }}
</div>
{% endfor %}
</div>
Upvotes: 0
Views: 58
Reputation: 688
product_detail
arguments should match your url mapping parameters in urls.py
. The function definition should has arguments id
, slug
:
def product_detail(request, id, slug):
...
Upvotes: 1