如何修复Django中的'名称'csrf'未定义'错误

时间:2019-01-08 10:28:58

标签: python django

我在WEB中获取了此代码,但这是针对Django 1.9的。我在项目中使用2.1。

我导入此:

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)

名称'csrf'未定义/回溯: img

1 个答案:

答案 0 :(得分:2)

请勿使用render_to_response。即使在Django 1.9中,它也已过时。

改为使用render。然后,您无需在视图中执行任何操作即可处理csrf保护。

将导入更改为

from django.shortcuts import render

get方法更改为:

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

以及post方法的最后一行:

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

最后,您可能希望在此处使用FormViewexample in the docs用于联系表格。