简体   繁体   English

用Django发送电子邮件; CSRF令牌丢失或不正确

[英]Sending an email with Django; CSRF token missing or incorrect

I'm having some issues with CSRF tokens in my Django project. 我在Django项目中遇到CSRF令牌问题。 What I am trying to do is allow a user to send a file to a specific email address using a form on my website. 我正在尝试做的是允许用户使用我网站上的表格将文件发送到特定的电子邮件地址。 The issue is the proverbial "CSRF token missing or incorrect". 问题是众所周知的“ CSRF令牌丢失或不正确”。 I've sifted through a few other questions; 我已经解决了其他几个问题。 however it seems as though my application is built differently than these other ones. 但是,似乎我的应用程序的构建与其他应用程序不同。 I am still very new to Web Development, let alone Django. 我对Web开发仍然很陌生,更不用说Django。 I think it may have to do with something in views, but it seems none of these solutions are useful for my purposes. 我认为这可能与视图中的某些内容有关,但是这些解决方案似乎都对我没有用。 If anyone has any idea of how we can put in the CSRF token or correct here, here are the files that were modified in order to add this email functionality: 如果有人对我们如何放入CSRF令牌或在此处更正有任何想法,请参阅以下文件,以便添加此电子邮件功能:

#views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.context_processors import csrf
from django import forms
from ReadMyPaper.feedbackEmail.forms import EmailForm

#Create your views here.
def send_email(request):
    if request.method != 'POST':
        form = EmailForm()
        return render_to_response('email.html', {'email_form': form})

    form = EmailForm(request.POST, request.FILES)      
    if form.is_valid():
        subject = form.cleaned_data['subject']
        message = form.cleaned_data['message']
        email = form.cleaned_data['email']
        attach = request.FILES['attach']
        try:
            mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [email])
            mail.attach(attach.name, attach.read(), attach.content_type)
            mail.send()
            #return render_to_response('Email.html', {'message': 'Sent email to %s'%email})
            args = {}
            args.update(csrf(request))
            args['form'] = EmailForm()
            #return render_to_response('email.html' , args)
            #return render_to_response(
            #'email.html', args
            #context_instance=RequestContext(request)
            return render_to_response("email.html", args)


        except:
      #     return render_to_response('admin/Error.html', {'message': 'Either the attachment is too  big or corrupt'})
            return render_to_response('loggedin.html')  

forms... 形式...

from django import forms

class EmailForm(forms.Form):
    email = forms.EmailField()
    subject = forms.CharField(max_length=100)
    attach = forms.Field(widget = forms.FileInput)
    message = forms.CharField(widget = forms.Textarea)

template... 模板...

{% block content %}
{{message}}
{% if email_form %}
<form method="POST" action ="." enctype="multipart/form-data">
        {% csrf_token %}
<br></br>
{{email_form.as_p}}

<label>&nbsp;</label><label>&nbsp;</label><label>&nbsp;</label>
<input type ="submit"  name = "send" value = "Send"/>
</form>
{% endif %}
{% endblock content %}

And the settings file... 还有设置文件...

#settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

# Host for sending e-mail.
EMAIL_HOST = 'smtp.gmail.com'

# Port for sending e-mail.
EMAIL_PORT = 587

# Optional SMTP authentication information for EMAIL_HOST.
EMAIL_HOST_USER = ‘myemail@gmail.com'
EMAIL_HOST_PASSWORD = ‘mypassword'
EMAIL_USE_TLS = True 

Obviously those are not the real email and password for gmail address. 显然,这些不是Gmail地址的真实电子邮件和密码。 I have an actual gmail I am using. 我使用的是实际的Gmail。

Replace the render_to_response() calls with the render() : render_to_response()调用替换为render()

from django.shortcuts import render

return render(request, 'email.html', {'email_form': form})

Or pass the RequestContext instance to the render_to_response() : 或将RequestContext实例传递给render_to_response()

return render_to_response("email.html", {'email_form': form},
                          context_instance=RequestContext(request))

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

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