简体   繁体   English

如何修复 Django 中的“名称‘csrf’未定义”错误

[英]How to fix 'name 'csrf' is not defined' error in Django

I took this code in the WEB but it was for Django 1.9.我在 WEB 中使用了这段代码,但它用于 Django 1.9。 I'm using 2.1 in my project.我在我的项目中使用 2.1。

I import this:我导入这个:

from django.shortcuts import render_to_response, reverse
from django.views import View
from django.core.mail import send_mail
from .forms import ContactForm
from blog import settings

class EContactsView(View):
    template_name = 'home/contacts.html'

def get(self, request, *args, **kwargs):
    context = {}
    context.update(csrf(request))
    context['contact_form'] = ContactForm()

    return render_to_response(template_name=self.template_name, context=context)

def post(self, request, *args, **kwargs):
    context = {}

    form = ContactForm(request.POST)

    if form.is_valid():
        email_subject = 'EVILEG :: Сообщение через контактную форму '
        email_body = "С сайта отправлено новое сообщение\n\n" \
                     "Имя отправителя: %s \n" \
                     "E-mail отправителя: %s \n\n" \
                     "Сообщение: \n" \
                     "%s " % \
                     (form.cleaned_data['name'], form.cleaned_data['email'], form.cleaned_data['message'])

        send_mail(email_subject, email_body, settings.EMAIL_HOST_USER, ['target_email@example.com'], fail_silently=False)

    return render_to_response(template_name=self.template_name, context=context)

name 'csrf' is not defined / traceback: img名称“csrf”未定义/回溯: img

Don't use render_to_response .不要使用render_to_response It was obsolete, even in Django 1.9.它已经过时了,即使在 Django 1.9 中也是如此。

Use render instead.改用render Then you don't have to do anything in the view to handle csrf protection.然后您无需在视图中执行任何操作来处理 csrf 保护。

Change the import to将导入更改为

from django.shortcuts import render

Change the get method to:get方法更改为:

def get(self, request, *args, **kwargs):
    context = {}
    context['contact_form'] = ContactForm()
    return render(request, template_name=self.template_name, context=context)

and the final line of the post method to:post方法的最后一行:

return render(request, template_name=self.template_name, context=context)

Finally, you might prefer to use FormView here.最后,您可能更喜欢在这里使用FormView The example in the docs is for a contact form. 文档中示例用于联系表单。

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

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