TypeError save()至少需要2个参数(给定1个)

时间:2015-08-31 06:41:34

标签: django django-models django-forms

我有类似错误的错误save()在Django项目中至少需要2个参数(给定1个)。

view.py文件

class DealsForm(ModelForm):
    class Meta:
        model = Product
        fields = ['title','description','category','price','sale_price','slug','active','update_defaults','user']
        exclude = ('user',)

model.py文件

class Product(models.Model):
    title = models.CharField(max_length=120)
    description = models.TextField(null=True, blank=True,max_length=200)
    category = models.ManyToManyField(Category, null=True, blank=True)
    price = models.DecimalField(decimal_places=2, max_digits=100, default=29.99)
    sale_price = models.DecimalField(decimal_places=2, max_digits=100,\
                                            null=True, blank=True)
    slug = models.SlugField(unique=True)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    active = models.BooleanField(default=True)
    update_defaults = models.BooleanField(default=False)
    user = models.ForeignKey(User)   

    def __unicode__(self):
        return self.title

    class Meta:
        unique_together = ('title', 'slug')

    def get_price(self):
        return self.price

    def get_absolute_url(self):
        return reverse("single_product", kwargs={"slug": self.slug})

    def save(self, request, *args, **kwargs):
        obj = super(DealsForm, self).save(commit=False, *args, **kwargs)
        obj.user = request.user 
        obj.save() 

你能解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

在调用request时,您似乎没有传递.save()对象。您还需要根据request的定义传递save()对象。

此外,请在.save()模型类中使用super()类参数调用DealsForm时检查Product函数。

修改

由于您只想在user对象上设置product,因此您可以执行以下操作:

def my_view(request):
    ...
    product = my_deals_form.save(commit=False) # get the product instance
    product.user = request.user # set the user on the product
    product.save() # save the object     

您无需覆盖save()方法。只需使用commit=False参数调用模型表单实例,将用户设置在product对象上,然后保存该对象。