Django:添加 if 语句以检查文件是否已在联系表单中上传

Django: Adding an if statement to check if file as been uploaded in a contact form

我有一个网站联系表,其中包含附加几个可选文件。填写表格后,将向员工发送一封电子邮件,其中包括表格输入以及作为电子邮件附件的这些文档。我想在我的 views.py 文件中的 msg.attach_file 命令之前添加一个 if 语句,以防止在从未上传文档的情况下附加文件。类似于...

if upload_file_type2 blank = false
    msg.attach_file('uploads/filetype2/')

我知道上面这行是不正确的,但我不确定如何编写表示表单条目为空的 if 语句。以下是相关文件。

Models.py

upload_file_type1 = models.FileField(upload_to=file_path1, blank=True)

upload_file_type2 = models.FileField(upload_to=file_path2, blank=True)

Views.py

def quote_req(request):
    submitted = False
    if request.method == 'POST':
        form = QuoteForm(request.POST, request.FILES)
        upload_file_type1 = request.FILES['upload_file_type1']
        upload_file_type2 = request.FILES['upload_file_type2']
        if form.is_valid():
            form.save()
            # assert false
            msg = EmailMessage('Contact Form', description, settings.EMAIL_HOST_USER, ['sample@mail.com'])
            msg.attach_file('file_path1')
            #THIS IS WHERE PROPOSED IF STATEMENT WOULD GO
            msg.attach_file('file_path2')
            msg.send()
            return HttpResponseRedirect('/quote/?submitted=True')
    else:
        form = QuoteForm()
        if 'submitted' in request.GET:
            submitted = True

你通常会这样做:

upload_file_type2 = request.FILES.get('upload_file_type2', None)
if upload_file_type2 is not None:
    # File is present, can attach
    # . . .

这可能是最好的方法。或者,也可以做类似下面的事情

if 'upload_file_type2' in request.FILES:
    # Here it is already not empty, and you can attach
    upload_file_type2 = request.FILES['upload_file_type2']
    # . . .