为什么我会收到“禁止”(CSRF令牌丢失或不正确)?

时间:2019-01-27 08:16:17

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

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

这通常是由于未使用RequestContext引起的。   “模板中使用了{%csrf_token%},但上下文为

这是表格。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>

1 个答案:

答案 0 :(得分:0)

在您的form.py中 更改

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

收件人

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

我的表单显示如下: enter image description here