Django 形式 is_valid() 总是返回 true。 Forms FileField 验证问题

问题描述 投票:0回答:0

在下面的表单中遇到验证上传文件的问题。
我不明白为什么

clean(self)
方法在我的
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

在我的下面

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)

它只是将我重定向到下一页

home
并显示成功消息。
在此先感谢您的帮助!

django-views django-forms django-validation
© www.soinside.com 2019 - 2024. All rights reserved.