我试图限制可以以表单上传的文件类型、大小和扩展名。该功能似乎有效,但未显示验证错误消息。我意识到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')
我缺少什么?