Encountered the problem of validation uploaded files at below Form.
I do not understand why clean(self) method does not work in my UpdateChecklistForm
forms.py:
class UpdateChecklistForm(forms.ModelForm):
class Meta:
model = CheckList
exclude = ['author']
isps_upload = forms.FileField(
label='ISPS report',
widget=forms.FileInput(attrs={'accept': 'pdf'}),
required=False
)
crewlist_upload = forms.FileField(
label='Crew List',
widget=forms.FileInput(attrs={'accept': 'pdf'}),
required=False
)
def clean(self):
self.check_isps()
self.check_crewlist()
return self.cleaned_data
def check_isps(self):
try:
content = self.cleaned_data["isps_upload"]
content_type = content.content_type.split('/')[0]
if content.size > int(MAX_UPLOAD_SIZE):
self.add_error(
'isps_upload',
_(f"Please keep file size under {(filesizeformat(MAX_UPLOAD_SIZE))}. "
f"Current file size {filesizeformat(content.size)}")
)
extension = os.path.splitext(content.name)[1]
VALID_EXTENSIONS = ['.pdf', '.doc', '.docx']
if not extension.lower() in VALID_EXTENSIONS:
self.add_error(
'isps_upload',
_('Only files with "pdf" or "doc/docx" extensions are supported, '
'received: "%s" file.' % extension)
)
return content
except AttributeError:
pass
def check_crewlist(self):
try:
content = self.cleaned_data["crewlist_upload"]
content_type = content.content_type.split('/')[0]
if content.size > int(MAX_UPLOAD_SIZE):
self.add_error(
'crewlist_upload',
_(f"Please keep file size under {(filesizeformat(MAX_UPLOAD_SIZE))}. "
f"Current file size {filesizeformat(content.size)}")
)
extension = os.path.splitext(content.name)[1] # [0] returns path+filename
VALID_EXTENSIONS = ['.pdf', '.doc', '.docx']
if not extension.lower() in VALID_EXTENSIONS:
self.add_error(
'crewlist_upload',
_('Only files with "pdf" or "doc/docx" extensions are supported, '
'received: "%s" file.' % extension)
)
return content
except AttributeError:
pass
here below my views.py
@login_required
def update_checklist(request, pk):
instance = get_object_or_404(CheckList, id=pk)
form = UpdateChecklistForm(request.POST or None, instance=instance)
if request.method == 'POST':
if form.is_valid():
instance = form.save(commit=False)
instance.author = request.user
ETA = request.POST['ETA']
try:
dispatcher = request.POST['dispatcher']
if dispatcher:
dispatcher = 'Done'
except Exception as e:
dispatcher = '-//-'
instance.author = request.user
try:
user = request.user
if hasattr(user, '_wrapped') and hasattr(user, '_setup'):
if user._wrapped.__class__ == object:
user._setup()
user = user._wrapped
if user:
user = user.last_name + " " + user.first_name
except Exception as e:
user = '-//-'
instance.save()
sendTelegram(...some stuff...)
messages.success(request, 'Success')
return redirect('home')
else:
return HttpResponse('error')
context = {
'form': form
}
return render(request, 'someurl/update.html', context)
It just redirect me to the next page home with success message.
Thanks in advance for any help!
It was necessary to add
request.FILESto updateView. Maybe this will be useful to somebody..