django - 在多个 django 模板中渲染表单函数

标签 django django-forms django-templates

我编写了一个函数,该函数从表单中捕获详细信息,并在表单提交后发送电子邮件。我怎样才能将此功能呈现给多个 django 模板,我可以在其中调用表单并执行此操作。 以下是相关功能..

def emailView(request):
    if request.method == 'GET':
        form = myform()
    else:
        form = myform(request.POST)
        if form.is_valid():
            subject='form Details'
            mobile = form.cleaned_data['mobile']
            email = form.cleaned_data['email']
            dummy = '\nMobile: '+mobile+'\nEmail: '+email'
            try:
                send_mail(subject, dummy, '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d1c0d8d8ccf5d2d8d4dcd99bd6dad8" rel="noreferrer noopener nofollow">[email protected]</a>', ['<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f1e0f8f8eca4d5f2f8f4fcf9bbf6faf8" rel="noreferrer noopener nofollow">[email protected]</a>', '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="284c5d4545511a684f45494144064b4745" rel="noreferrer noopener nofollow">[email protected]</a>'])
                messages.success( request, " Thank you !! For contacting.')
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('email')
    return render(request, "my_app/email.html", {'form': form})

最佳答案

您可以使用 include 标签来执行此操作。尝试以下方法。

将以下内容视为 urls.py 中的网址

path('your_form/', views.emailView, name='myform'),

您可以使用以下标记调用任意数量的模板函数。

#template1.html

<form method="post" action="{% url 'myform' %}">
{% include 'yourapp/email.html' %}
<button type="submit">Submit</button>

#template2.html

<form method="post" action="{% url 'myform' %}">
{% include 'yourapp/email.html' %}
<button type="submit">Submit</button>

关于django - 在多个 django 模板中渲染表单函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60506274/

相关文章:

html - Bootstrap 移动导航栏下拉菜单是透明的

django - 检测用户在单击后退按钮时是否进入页面

python - Django:模型更新时表单值不更新

django-models - 保存方法中的 force_update

python - Django 不会扩展到父文件夹中的 base.html

python - Django:如何使用自定义模板制作表单?

python - Mac OS X - 环境错误 : mysql_config not found

python - 类型错误 : string indices must be integers When Checking array with dictionaries

Django 表单 : how to dynamically create ModelChoiceField labels

django - 如何打印选择字段的字符串值