Django从url中缺少参数>视图

时间:2014-03-25 22:46:21

标签: python django

我在尝试访问网址时遇到此错误... / polls / products /

TypeError at /polls/products/

productindex() takes exactly 2 arguments (1 given)

我已经测试了附加到我认为合适的视图的网址,这很好,所以我猜测我的观点有问题。

models.py

class Product(models.Model):
    product_name = models.CharField(max_length=200)
    product_description = models.TextField()
    def __unicode__(self):
        return self.product_name

class Image(models.Model):
    product_image = models.ForeignKey(Product)
    image = models.ImageField(upload_to='image')

views.py

def productindex(request, product_image_id):
    product = get_object_or_404(Product, pk=product_image_id)
    return render(request, 'polls/products.html', {'product': product})

urls.py

from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
    url(r'products/$', views.productindex, name='productindex'),
)

1 个答案:

答案 0 :(得分:0)

视图期待request和产品pk。现在它正在收到请求但不是pk。

以下是将product.pk传递给视图的一种方法。

... urls.py

from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
    url(r'products/(?P<pk>\d+)/$', views.productindex, name='productindex'),
)

你的HTML应该是这样的......

<a href="{% url 'productindex' product.pk %}">{{ product }}</a>