Reputation: 129
I've seen many questions about django validators not giving the correct responses, but I have a different problem. Mine doesn't even trigger despite being copied from the Django docs example. Here's what I have:
models.py
def content_file_name(instance, filename):
ext = ''.join(filename.split())[:-4]
foldername = "%s/%s" % (uuid.uuid4(), ext)
return '/'.join(['documents', str(foldername), filename])
class Document(models.Model):
docfile = models.ImageField(upload_to=content_file_name)
class DocumentImage(models.Model):
imagefile = models.ImageField(upload_to=content_file_name)
image = models.ForeignKey(Document, related_name='Image', null=True, on_delete=models.CASCADE)
views.py
def documentlist(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = form.save()
newdoc.create_documentfiles()
messages.add_message(request, messages.INFO, "Saved")
return HttpResponseRedirect(reverse('list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render(
request,
'list.html',
{'documents': documents, 'form': form}
)
forms.py
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('docfile',)
def clean_image(self):
file = self.cleaned_data.get('docfile')
if file:
if imghdr.what(file.read()) != "gif":
raise forms.ValidationError("Please upload a .gif file")
print('complete');
file.seek(0)
return file
I have even tried setting the forms.py like this:
def clean_image(self):
print('test')
raise forms.ValidationError("Please upload a .gif file")
And I still get neither ValidationError
nor test
printed in console. Did anyone encounter such a problem?
Upvotes: 0
Views: 173
Reputation: 15370
Your validation function's name is clean_image
, but there is no image
field on form
fields = ('docfile',)
So it doesn't get called. It should be called clean_docfile
if you want to validate docfile
field
The
clean_<fieldname>()
method is called on a form subclass – where<fieldname>
is replaced with the name of the form field attribute. This method does any cleaning that is specific to that particular attribute, unrelated to the type of field that it is. This method is not passed any parameters. You will need to look up the value of the field in self.cleaned_data and remember that it will be a Python object at this point, not the original string submitted in the form (it will be in cleaned_data because the general field clean() method, above, has already cleaned the data once).
https://docs.djangoproject.com/en/1.11/ref/forms/validation/
Upvotes: 2
Reputation: 2003
Your clean method name should be renamed as
def clean_docfile(self):
print('test')
raise forms.ValidationError("Please upload a .gif file")
Upvotes: 1