Pratz Wolfheart Pratz Wolfheart - 8 months ago 46
Python Question

Django Contact Form Attachment showing 'This field is required.' What am I doing Wrong?

from django.conf import settings
from django.core.mail import EmailMessage,send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import ContactForm

def email(request):
if request.method == 'GET':
form = ContactForm()
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
name = form.cleaned_data['name']
phone = form.cleaned_data['phone']
image1 = request.FILES['image1']
full_message = str([from_email,name.upper(), phone, message])

email = EmailMessage(subject.upper(),full_message,from_email+'<>',[''],headers = {'Reply-To': from_email })
email.attach(,, image1.content_type)
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "email.html", {'form': form})

def success(request):
return HttpResponse('Success! Thank you for your message.')

from django import forms

class ContactForm(forms.Form):
name = forms.CharField(required=True)
phone = forms.CharField(required=True)
from_email = forms.EmailField(required=True)
subject = forms.CharField(required=True)
message = forms.CharField(widget=forms.Textarea, required=True)
image1 = forms.Field(label='sample photo', widget = forms.FileInput, required = True )

If I send the mail with out attachment its working but when i add an attachment file it shows "This field is required." in the webpagethis image is a screenshot of the problem i want to know what am doing wrong and how can i send and mail with the attachment

Answer Source

You need to pass FILES into the form as well, since it has a file field:

    form = ContactForm(request.POST, request.FILES)

This is all explained in the documentation for uploading files.