Django 文件上传与电子邮件

发布于 2024-08-30 06:06:05 字数 1155 浏览 3 评论 0原文

我正在尝试附加带有联系表格的文件。我的表单和视图代码如下所示:

if request.method == 'POST':
    form = UploadCVForm(request.POST, request.FILES)
    if form.is_valid(): # All validation rules pass
        subject = "CV Sent from BiztechAfrica"
        sender = form.cleaned_data['email']
        message = "Some message goes in here"
        name = form.cleaned_data['name']
        recipients = ['[email protected]']
        cv_file = request.FILES['cv_file']
        mail = EmailMessage(subject, message, sender, recipients)
        mail.send()

        return HttpResponse('Thanks') # Redirect after POST
else:
    form = UploadCVForm()

这是我的 forms.py:

class UploadCVForm(forms.Form):
    subject = "CV Sent from BiztechAfrica"
    name = forms.CharField(max_length=128)
    email = forms.EmailField()
    cv_file = forms.Field(label='CV', widget = forms.FileInput,   required = True )

电子邮件工作正常,但我无法附加文件,因为它一直给我一个表单错误,即文件上传输入字段不能为空,尽管我已选择要上传的文件。

有什么想法吗?我仍然是 Django 和 Python 的新手......

I am trying to attach a file with a contact form. My code looks like this for the form and view:

if request.method == 'POST':
    form = UploadCVForm(request.POST, request.FILES)
    if form.is_valid(): # All validation rules pass
        subject = "CV Sent from BiztechAfrica"
        sender = form.cleaned_data['email']
        message = "Some message goes in here"
        name = form.cleaned_data['name']
        recipients = ['[email protected]']
        cv_file = request.FILES['cv_file']
        mail = EmailMessage(subject, message, sender, recipients)
        mail.send()

        return HttpResponse('Thanks') # Redirect after POST
else:
    form = UploadCVForm()

This is my forms.py:

class UploadCVForm(forms.Form):
    subject = "CV Sent from BiztechAfrica"
    name = forms.CharField(max_length=128)
    email = forms.EmailField()
    cv_file = forms.Field(label='CV', widget = forms.FileInput,   required = True )

The email works fine, but I cant attach the file because it keeps giving me a form error that the file upload input field can't be empty although I have selected a file to upload.

Any ideas? I am still a newb to Django and Python...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

謌踐踏愛綪 2024-09-06 06:06:05

我敢打赌,您在表单模板中遗漏了enctype="multipart/form-data"

<form action="/wherever/" method="POST" enctype="multipart/form-data">

如果我花在尝试跟踪此类错误上的每一分钟都得到一分钱的话.. 。

I'd bet money you left off enctype="multipart/form-data" from your form template:

<form action="/wherever/" method="POST" enctype="multipart/form-data">

If I had a penny for every minute I've spent trying to track errors like that down...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文