使用带有附件且不需要数据库的 django 自定义表单发送电子邮件

Sending an email with django custom forms with an attachment and without the need of a database

我正在尝试创建一个职位空缺表,申请人可以在其中提交简历。 当我出于某种原因提交表单时,文件字段被清除并告诉我附上一个。我不想在这种方法中包含数据库,因为我觉得它可能会消耗数据库中的 space。 可以吗?

views.py

def contact_us(request):
    if request.method == "POST":
        form = ContactUsEmploymentForm(request.POST, request.FILES)
        if form.is_valid():
            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')
            designation = form.cleaned_data.get('designation')
            expected_salary = form.cleaned_data.get('expected_salary')
            cv = form.cleaned_data.get('cv')
            email = form.cleaned_data.get('email')
            content = form.cleaned_data.get('content')

            content = f""" WARNING: THIS IS AN EMAIL SENT BY A USER \n
First name: {first_name}
Last name: {last_name}
User's Email: {email}\n
Applying for: {designation}
Expected salary: {expected_salary}
Body:
{content}
"""
            send_mail(
                "Candidate applying for a vacancy",
                content,
                'my_email',
                ['my_email'],
                fail_silently=False,
            )
            return render(request, "homepage/email_confirmation.html")

    else:
        form = ContactUsEmploymentForm()
    return render(request, "homepage/contact_us.html", {"form":form})

forms.py

class ContactUsEmploymentForm(forms.Form):
    first_name = forms.CharField(max_length=80)
    last_name = forms.CharField(max_length=80)
    email = forms.EmailField()
    designation = forms.ModelChoiceField(queryset=Vacancy.objects.filter().all())
    expected_salary = forms.CharField(max_length=80)
    cv = forms.FileField()
    content = forms.CharField(max_length=800, widget=forms.Textarea)

和 HTML 文件

<div class="contact_us_container p-2">
    <div class="contact_us_wrapper mt-5 mb-2">

        <h2 class="font_1 big_font mt-5">Talk to us today!</h2>
        <div class="container">
            <form method="POST">
                {% csrf_token %}
    
                {{form | crispy}}
                <button class="btn btn-outline-dark ">Send</button>
            </form>
        </div>

    </div>
</div>

如有任何帮助,我们将不胜感激。 谢谢!

Django 文档说明如下:

请注意,如果请求方法是 POST 并且 post 请求具有属性 enctype="multipart/form-data",则 request.FILES 将仅包含数据。

示例: 表单方法="post" enctype="multipart/form-data"

参见:

https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/