繁体   English   中英

禁止(CSRF 令牌丢失或不正确。):Django 表单

[英]Forbidden (CSRF token missing or incorrect.): Django form

我正在尝试使用 Django 将电子邮件帐户订阅到时事通讯,当我尝试单击“开始”按钮时,我收到错误禁止(CSRF 令牌丢失或不正确。):

这是 views.py 方法:

def newsletterSubscribe(request):
try:
    form = NewsletterUserSignUpForm(request.POST or None)

    if form.is_valid():
        instance = form.save(commit=False)
        if NewsletterUser.objects.filter(email=instance.email).exists():
            messages.warning(request, _('Alerta! El correo ingresado ya se encuentra suscrito.'),
                             'alert alert-warning alert-dismissible')
        else:
            instance.save()
            messages.success(request, _('Correo agregado con exito!'),
                             'alert alert-success alert-dismissible')

            subject = _('Gracias por unirse a nuestro boletín')
            message = _("""Bienvenido al boletín de ADA Robotics. Si deseas no estar suscrito visita: 
                        https://127.0.0.1:8000/unsubscribed""")
            msg = MIMEMultipart('alternative')
            msg['From'] = settings.EMAIL_HOST_USER
            msg['To'] = instance.email
            msg['Subject'] = subject
            part = MIMEText(message, 'plain')
            msg.attach(part)

            mail = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT, timeout=20)
            mail.starttls()

            """
                template = get_template("myapp/sample_template.html")
                context = Context(context_data)
                body_html = template.render(context_data)
                body_text = strip_tags(body_html)
                part1 = MIMEText(body_text, 'plain')
                part2 = MIMEText(body_html, 'html')
                msg.attach(part1)
                msg.attach(part2)
            """

            emailto = [instance.email]
            mail.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
            mail.sendmail(settings.EMAIL_HOST_USER, emailto, msg.as_string())
            mail.quit()

            """from_email = settings.EMAIL_HOST_USER
                to_email = [instance.email]

                send_mail(subject=subject, from_email=from_email, recipient_list=to_email, message=message, fail_silently=False)"""

    context = {
        'form': form,
    }
    template = 'subscribed.html'
    #return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    return render(request, template, context)
except Exception as ex:
    return render(request, '404.html')

这是模板代码:

<form id="newsletterForm" action="{% url "newsletterSubscribe" %}" method="POST" class="mr-4 mb-3 mb-md-0">
                            {% csrf_token %}
                            <div class="input-group input-group-rounded">
                                <input class="form-control form-control-sm bg-light" placeholder="Email Address" name="email" id="newsletterEmail" type="text">
                                <span class="input-group-append">
                                    <button class="btn btn-light text-color-dark" type="submit"><strong>GO!</strong></button>
                                </span>
                            </div>
                        </form>

这是我的 urls.py:

path('contact/', contact, name="contact"),
path('subscribed/', newsletterSubscribe, name="newsletterSubscribe"),

我已将中间件添加到我的设置文件中,并迁移数据库以创建已创建的表。

我想要做的是一个时事通讯表单,它位于模板的 base.html 中,因此它可以在 Web 应用程序的所有其他页面中使用。

您需要将包含表单对象的上下文传递给渲染函数。 您正在加载表单因为它都是 html,但{% csrf_token %}未加载,因为您尚未将表单对象传递到模板中。

https://docs.djangoproject.com/en/3.0/topics/http/shortcuts/#render

render(request, template_name, context=None, content_type=None, status=None, using=None)

你的将是:

return render(request, template, context)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM