我有一个视图可以验证表单中的数据,该表单仅包含有关项目的一些基本信息。is_valid
即使在阅读完
这篇文章后,我也对该方法在这里的工作方式感到困惑。如果用户没有输入一些必填字段,例如名称或图像 1,我希望他们在页面上看到“此字段是必需的”或类似性质的错误。我想如果form.is_valid
返回False
,这些消息会自动在页面上为用户提出。或者我是否需要为每个字段指定我希望用户看到的错误消息?
#view
def sell(request):
if request.method == "POST":
form = AddItem(request.POST, request.FILES)
if form.is_valid():
item = form.save(commit=False)
item.user = request.user
item.is_active = True
item.slug = slugify(item.name)
item.save()
return HttpResponseRedirect('thanks.html')
else:
form = AddItem()
return render_to_response('forsale.html', locals(), context_instance=RequestContext(request))
#form
class AddItem(forms.ModelForm):
name = forms.CharField(label="Title")
class Meta:
model = Item
exclude = ('user','slug','is_active',)
#model
class Item(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=75)
slug = models.SlugField(max_length=50, unique=True)
is_active = models.BooleanField(default=True, blank=True)
image1 = models.ImageField(upload_to='img')
image2 = models.ImageField(upload_to='img', blank=True)
image3 = models.ImageField(upload_to='img', blank=True)
image_caption1 = models.CharField(max_length=200, blank=True)
image_caption2 = models.CharField(max_length=200, blank=True)
image_caption3 = models.CharField(max_length=200, blank=True)
price = models.DecimalField(max_digits=8, decimal_places=2)
quantity = models.IntegerField(default=1)
description = models.TextField()
created = models.DateTimeField(auto_now_add=True)
shipping_price = models.DecimalField(decimal_places=2, max_digits=6)
categories = models.ManyToManyField(Category)