我正在尝试限制可以在表单中上传的文件类型,大小和扩展名。该功能似乎有效,但验证错误消息未显示。我意识到if file._size > 4*1024*1024
可能不是最好的方式 - 但我稍后会处理它。
这是forms.py:
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name', 'description', 'url', 'product_type', 'price', 'image', 'image_url', 'product_file']
labels = {
'name': 'Product Name',
'url': 'Product URL',
'product_type': 'Product Type',
'description': 'Product Description',
'image': 'Product Image',
'image_url': 'Product Image URL',
'price': 'Product Price',
'product_file': 'Product Zip File',
}
widgets = {
'description': Textarea(attrs={'rows': 5}),
}
def clean(self):
file = self.cleaned_data.get('product_file')
if file:
if file._size > 4*1024*1024:
raise ValidationError("Zip file is too large ( > 4mb )")
if not file.content-type in ["zip"]:
raise ValidationError("Content-Type is not Zip")
if not os.path.splitext(file.name)[1] in [".zip"]:
raise ValidationError("Doesn't have proper extension")
return file
else:
raise ValidationError("Couldn't read uploaded file")
......这是我用于该表格的视图:
def post_product(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ProductForm(data = request.POST, files = request.FILES)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
product = form.save(commit = False)
product.user = request.user
product.likes = 0
product.save()
# redirect to a new URL:
return HttpResponseRedirect('/products')
我错过了什么?
在您的视图中,无论表单是否有效,您都在进行重定向 - 因此Django无法显示表单错误。
执行此操作的常规方法是在is_valid()
为False
时重新呈现表单:
if form.is_valid():
# process the data in form.cleaned_data as required
product.save()
# redirect to a new URL - only if form is valid!
return HttpResponseRedirect('/products')
else:
ctx = {"form": form}
# You may need other context here - use your get view as a template
# The template should be the same one that you use to render the form
# in the first place.
return render(request, "form_template.html", ctx}
您可能需要考虑使用基于类的FormView,因为它处理重新呈现带有错误的表单的逻辑。这比编写两个单独的get和post视图来管理表单更简单,更容易。即使您不这样做,也可以更容易地使用单个视图来处理表单的GET和POST。