【发布时间】:2020-05-14 05:20:13
【问题描述】:
我正在尝试创建模型表单并将其存储在数据库中。模型代表产品,具有类别、图片、价格等字段。
这是模型
class Product(models.Model):
categories = (("Books", "Books/Study Materials"),
("Notebooks", "Notebooks/Rough Pads"),
("Equipments", "Equipments/Tools"),
("Cloths", "Cloths/Uniforms"),
("Sports", "Sports/Sportswear"),
("Miscellaneous", "Miscellaneous"))
user = models.ForeignKey(User, on_delete = models.CASCADE)
date_posted = models.DateTimeField(default = timezone.now)
category = models.CharField(max_length = 13, choices = categories, default = "Miscellaneous")
description = models.CharField(max_length = 75, null = True, blank = True)
image = models.ImageField(default = "product/default.png", upload_to = "product")
price = models.PositiveIntegerField()
def __str__(self):
return f"{self.category} by {self.user.username} for {self.price}"
def save(self, *args, **kwargs):
super().save()
image = Image.open(self.image.path)
image.thumbnail((600, 600), Image.ANTIALIAS)
image = image.crop(((image.width - 600)//2, (image.height - 400)//2, (image.width + 600)//2, (image.height + 400)//2))
image.save(self.image.path)
这是同一型号的表格
class ProductAddForm(forms.ModelForm):
description = forms.CharField(max_length = 75, widget = forms.TextInput(attrs = {'placeholder': 'Description'}), help_text = "Not more than 75 characters")
image = forms.ImageField(required = False)
price = forms.IntegerField(required = False, widget = forms.TextInput(attrs = {'placeholder': 'Price'}))
class Meta:
model = Product
fields = ('category', 'description', 'image', 'price')
def clean_description(self, *args, **kwargs):
description = self.cleaned_data.get('description')
if len(description) == 0:
raise forms.ValidationError('Description is required!')
if len(description) > 75:
raise forms.ValidationError(f'Description should contains at most 75 characters, but bot {len(description)} characters!')
return description
def clean_price(self, *args, **kwargs):
price = self.cleaned_data.get('price')
if len(str(price)) == 0:
raise forms.ValidationError('Product price is required!')
elif price < 0:
raise forms.ValidationError('Negative price..... seriously?')
return price
下面是我使用 django 的通用 CreateView 创建的视图
class product_add(CreateView):
model = Product
form_class = ProductAddForm
template_name = 'Product/product_add.html'
def form_valid(self, form, *args, **kwargs):
form.instance.author = self.request.user
return super().form_valid(form)
上面我定义了form_valid 方法来将产品的用户设置为当前用户。
但是在提交表单的时候,还是报错-
IntegrityError at /product/add/
NOT NULL constraint failed: Product_product.user_id
即使我没有定义form_valid,我仍然会遇到同样的错误!
错误在super.save(),它说Error in formatting: RelatedObjectDoesNotExist: Product has no user.
【问题讨论】:
标签: python django django-models django-forms django-views