【问题标题】:Why am I receiving Forbidden (CSRF token missing or incorrect)?为什么我收到 Forbidden(CSRF 令牌丢失或不正确)?
【发布时间】:2019-06-20 12:39:04
【问题描述】:

我收到了 禁止(CSRF 令牌丢失或不正确) 我尝试了在 Stack Overflow 上找到的不同解决方案,但我无法修复它! 我曾尝试使用render_to_response,但当我这样做时,我收到此错误:

这通常是由于没有使用 RequestContext 造成的。 "模板中使用了 {% csrf_token %},但上下文 "

这是forms.py

from django import forms


class AskForm(forms.Form):
    name = forms.CharField(
        max_length=30,
        widget=forms.TextInput(
            attrs={
                'placeholder': 'Write your name here',
                'class': 'ask-page-input',
                'label': 'Student Name',
            }
        ))
    email = forms.EmailField(
        max_length=254,
        widget=forms.EmailInput(
            attrs={
                'placeholder': 'Write your Email here',
                'class': 'ask-page-input',
                'label': 'Email',
            }
        ))
    subject = forms.CharField(
        max_length=50,
        widget=forms.TextInput(
            attrs={
                'placeholder': 'Write your Question or Related Subject here',
                'class': 'ask-page-input',
                'label': 'Subject',
            }
        ))

    message = forms.CharField(
        max_length=2000,
        widget=forms.Textarea(
            attrs={
                'placeholder': 'Write your message here',
                'class': 'ask-page-input',
                'label': 'Message',
            }
        ))

    source = forms.CharField(  # A hidden input for internal use
        max_length=50,  # tell from which page the user sent the message
        widget=forms.HiddenInput()
    )

    def clean(self):
        cleaned_data = super(ContactFrom, self).clean()
        name = cleaned_data.get('name')
        email = cleaned_data.get('email')
        subject = cleaned_data.get('subject')
        message = cleaned_data.get('message')
        if not name and not email and not subject and not message:
            raise forms.ValidationError('You have to write something!')

这是views.py

from django.shortcuts import render, redirect, render_to_response
from forms import AskForm

def askpage_form(request):
    if request.method == 'POST':
        form = AskForm(request.POST)
        if form.is_valid():
            pass  # does nothing, just trigger the validation
    else:
        form = AskForm()
    return render(request, "ask.html",  {'form': form,  })

这是html文件

  <!DOCTYPE html>
  <html lang="en" dir="ltr">
    <head>
      <meta charset="utf-8">
      <title>Physics Quizzes Ask</title>
    </head>
    <body>
      <form method="post">
        {% csrf_token %}
        {{ form }}
        <button type="submit" name="button">Submit</button>
      </form>
    </body>
  </html>

【问题讨论】:

  • 您是否尝试清除缓存?
  • 是的,我试过这样做,但没有成功! @ShafikurRahman
  • settings.py 中 MIDDLEWARE_CLASSES 中的 'django.middleware.csrf.CsrfViewMiddleware' 是否可用
  • 是的,它可用。

标签: django django-forms django-templates django-views


【解决方案1】:

在您的form.py 改变这个

def clean(self):
    cleaned_data = super(ContactForm, self).clean()

def clean(self):
    cleaned_data = super(AskForm, self).clean()

我的表单显示如下:

【讨论】:

  • 模板中没有显示表单,只有html按钮。
  • 你渲染 ask.html 吗?
  • 是的,在浏览器上,我输入 127.0.0.1:8000/ask,除了提交按钮什么都没有。
  • 我测试代码并将我的输出添加到我的答案中。你看到任何错误吗?
  • 我什么也没看到,表单本身没有出现,只有提交按钮出现,当我点击它时,它说 CSRF 验证失败。请求中止。
猜你喜欢
  • 2017-09-01
  • 2013-12-03
  • 1970-01-01
  • 2021-07-14
  • 2019-11-03
  • 1970-01-01
  • 2011-12-26
  • 2014-03-29
  • 1970-01-01
相关资源
最近更新 更多