Pratz Wolfheart Pratz Wolfheart - 10 days ago 6
Python Question

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

Views.py

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()
else:
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])

try:
email = EmailMessage(subject.upper(),full_message,from_email+'<sender@gmail.com>',['pratirup8@gmail.com'],headers = {'Reply-To': from_email })
email.attach(image1.name, image1.read(), image1.content_type)
email.send()
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.')


Forms.py

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

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.