【问题标题】:How to get rid of the csrf validation with EmailMultiAlternatives in DJANGO?如何在 DJANGO 中使用 EmailMultiAlternatives 摆脱 csrf 验证?
【发布时间】:2014-09-22 19:50:50
【问题描述】:

我想向某个地址发送 html 电子邮件。

这是我的代码的一部分:

views.py

def addNewEvent(request):   
    try:
        eventStatus = EventStatus.objects.filter(event=request.GET["id"])[0]

        #try to send the mail
        html = get_template('mail.html')
        d = Context({ 'username': usuario.name,'title':'Testing mail!!','eventStatusId': str(eventStatus.id)})

        html_content = html.render(d)

        msg = EmailMultiAlternatives('Testing yo','Skyforger!', 'mymail@gmail.com', [mail2@gmail.com])
        msg.attach_alternative(html_content, "text/html")
        msg.send()

        print('EventStatus id '+str(eventStatus.id))
    except Exception, e:
        print ('the error %s',(str(e)))

    response = getBaseJSON()
    response["event_id"]= eventStatus.id
    return HttpResponse(json.dumps(response), content_type="application/json")

ma​​il.html

<html>
    <body>
        <h1>{{title}}</h1>
        <h2>Hi {{username}}</h2>
        <h3>Message to friend</h3>
        <form action="http://localhost:8000/confirmEvent" method="POST">
            {% csrf_token %}
            <input type="hidden" name="id" value="{{eventStatusId}}">
            <textarea name="message_to_friend"></textarea><br>
            <input type="submit" value="I'LL BE THERE!!">
        </form>
    </body>
</html>

邮件发送正常,但提交表单时,显示此错误:

禁止 (403) CSRF 验证失败。请求中止。

我找不到解决该错误的方法。

我关注了很多这样的答案:

https://stackoverflow.com/a/10388110

Forbidden (403) CSRF verification failed. Request aborted. Even using the {% csrf_token %}

没有成功。

如何在 html 邮件中发送表单以避免 CSRF 错误。

【问题讨论】:

  • 我看到您已经看到了答案,但我没有在您的表单中看到{% csrf_token %}
  • 需要明确的是,mail.html 是否呈现并发送给在邮件客户端中打开它的用户? CSRF 令牌对应于 当前用户,而不是将在邮件中打开它的用户。此外,由于您使用 Context() 来呈现表单,因此很可能不包含 CSRF 令牌。您应该使用 RequestContext:docs.djangoproject.com/en/dev/ref/contrib/csrf
  • @mgnb 在我的情况下我应该如何使用 RequestContext ?我读到它必须用作 render_to_response 中的参数,但我没有使用该方法

标签: django django-views csrf django-csrf


【解决方案1】:

您可以使用 csrf_exempt 装饰器来禁用特定视图的 CSRF 保护。

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def someview():

不建议禁用 csrf ,但如果你愿意,可以试试这个:)

【讨论】:

    【解决方案2】:

    我用参数 context_instance=RequestContext(request) 将 render() 替换为 render_to_string(),现在可以正常工作了。

    def addNewEvent(request):   
            try:
                eventStatus = EventStatus.objects.filter(event=request.GET["id"])[0]
    
                #try to send the mail
                html = get_template('mail.html')
                d = Context()
    
                html_content = render_to_string('mail.html',{ 'username': usuario.name,'title':'Testing mail!!','eventStatusId': str(eventStatus.id)}, context_instance=RequestContext(request)) 
                msg = EmailMultiAlternatives('Testing yo','Skyforger!', 'mymail@gmail.com', [mail2@gmail.com])
                msg.attach_alternative(html_content, "text/html")
                msg.send()
    
                print('EventStatus id '+str(eventStatus.id))
            except Exception, e:
                print ('the error %s',(str(e)))
    
            response = getBaseJSON()
            response["event_id"]= eventStatus.id
            return HttpResponse(json.dumps(response), content_type="application/json")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-11
      • 2018-09-15
      • 2016-05-07
      • 2013-05-03
      • 2012-11-04
      • 2016-03-03
      • 2011-09-28
      • 2015-03-18
      相关资源
      最近更新 更多