I'm trying to restrict file type, size and extension that can be uploaded in a form. The functionality seems to work, but the validation error messages are not showing. I realize that if file._size > 4*1024*1024
is probably not the best way - but I'll deal with that later.
Here's the 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")
...and here's the view I'm using for that form:
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')
What am I missing?