Django:无法将关键字参数传递给基于类的表单

时间:2016-03-05 08:10:35

标签: python django

我有一个包含模型products的列表,每个products实例都有自己的variants。如果不使用管理员,我想在products/<pk>/查看我的产品,然后使用基于类的表单转到products/<pk>/add-variant/,为每个产品实例添加变体。我的问题是,我不知道如何将产品实例的ID传递给CreateVariant表单,因为我一直收到错误:

  

反转&#39; variant-create&#39;有参数&#39;(&#39;&#39;,)&#39;和关键字参数&#39; {}&#39;未找到。尝试了1种模式:[&#39;供应商/产品/(?P \ d +)/ add-variant / $&#39;]

models.py:

class Product(models.Model):
    name = models.CharField(max_length = 120)
    description = models.TextField(blank=True,null=True)
    main_image = models.ImageField(upload_to=image_upload_location)
    price = models.DecimalField(decimal_places=2, max_digits=20)
    available = models.BooleanField(default=True)
    categories = models.ManyToManyField('Category', blank=True)

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('product-detail', kwargs={'pk':self.pk})

class Variant(models.Model):
    name = models.CharField(max_length=120)
    description = models.TextField(blank=True,null=True)
    variant_image = models.ImageField(upload_to=image_upload_location, null=True)
    price = models.DecimalField(decimal_places=2,max_digits=20)
    available = models.BooleanField(default=True)
    product = models.ForeignKey(Product)
    store = models.ForeignKey(Store)

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('product-detail', kargs={'pk': self.product_id})

views.py:

#...

class ProductDetailView(DetailView):
        model = Product
        template_name = 'gravel/product_detail.html'

class VariantCreate(CreateView):
            model = Variant
            template_name = 'gravel/add_variant.html'
            fields = ['name', 'description', 'variant_image', 'price', 'available']

class VariantUpdate(UpdateView):
    model = Variant
    template_name = 'gravel/update_variant.html'
    fields = ['name', 'description', 'variant_image', 'price', 'available']

class VariantDelete(DeleteView):
    model = Variant
    success_url = reverse_lazy('product_detail_view')

urls.py:

urlpatterns = [

    url(r'^$', ProductListView.as_view(), name="product-list" ),
    url(r'^(?P<pk>\d+)/$', ProductDetailView.as_view(), name="product-detail"),
    url(r'^(?P<pk>\d+)/add-variant/$', VariantCreate.as_view(), name="variant-create"),
#... ]

当然,Stack上有一些类似的问题,但是没有一个能够帮助我。我无法找出通过给定id实例的products的任何方法,以便在我去{例如products/1/add-variant时,它会为产品添加该变体。 id = 1.但是从上面的错误可以看出,我无法传递任何变量。

0 个答案:

没有答案