Search code examples
djangoemaildjango-formsemail-attachmentscontact-form

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


I have a website contact form that involves attaching several optional documents. Once the form has been filled out, an email is sent to an employee which includes form inputs along with these documents as email attachments. I am looking to add an if statement before the msg.attach_file command in my views.py file that prevents attaching the file if a document was never uploaded. Something along the lines of...

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

I know that above line is incorrect, but I am unsure of how to write an if-statement that says the form entry was blank. Below are relevant files.

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

Solution

  • You would generally do something like this:

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

    That's probably the best method. Alternatively, can also do something like the following

    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']
        # . . .