我正在创建一个市场,选定的用户可以在其商店中购物并对其产品进行CRUD。 创建Createview类时出现错误。我需要用户添加新产品,根据商店模型返回自己的商店名称的表格,但看起来存在上述错误。 以下是我的应用程序:
models.py
class Shop(models.Model):
shop_name = models.CharField(max_length=120)
owner = models.OneToOneField(User,on_delete=models.CASCADE, related_name="owner")
def __str__(self):
return self.shop_name
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,)
shop = models.ForeignKey (Shop, on_delete=models.CASCADE, related_name='shop')
category = models.ForeignKey(Category, verbose_name ='Categoria',on_delete=False )
title = models.CharField(max_length=120)
slug = models.SlugField(blank= True, null=True, unique = True)
views.py
class ProductCreateView(LoginRequiredMixin,SubmitBtnMixin, CreateView):
model = Product
form_class = ProductForm
template_name = 'form.html'
success_url = '/products/list'
submit_btn = 'Add Product'
def form_valid(self, form):
new_product = form.save(commit=False)
user = self.request.user
s = Shop.objects.get (owner=user)
new_product.shop = s
new_product.save()
return super (ProductCreateView, self).form_valid(form)
FORM.PY
class ProductForm(ModelForm):
class Meta:
model = Product
fields = ['category', 'title', 'description', 'price', 'image']
exclude = ['shop']
答案 0 :(得分:1)
在您的产品模型中,我没有看到属性“描述”,但是在您的表单中,您指定了字段“描述”。尝试在产品模型的用户字段中添加null = True,blank = True。
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True)
shop = models.ForeignKey (Shop, on_delete=models.CASCADE, related_name='shop')
category = models.ForeignKey(Category, verbose_name ='Categoria',on_delete=False )
title = models.CharField(max_length=120)
slug = models.SlugField(blank= True, null=True, unique = True)