首页 > 解决方案 > CSRF 验证失败。请求中止 - 即使添加 {% csrf_token %}

问题描述

我收到 CSRF 验证失败。请求中止错误。我做了广泛的研究,一切都指出将 {% csrf_token %} 添加到带有 POST 表单的模板标签中,我这样做了,但仍然遇到同样的错误。

这是我为网站设置的设置。

import os
from pathlib import Path

DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    #DINOSAHR DESIGN Installed Apps
    'leonebraiding'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'LeoneBraidingSite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'LeoneBraidingSite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/Chicago'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = 'static/static/'
MEDIA_URL = 'uploads/'

STATICFILES_DIRS = [
    BASE_DIR / "static",
    '/var/www/static/',
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/uploads')



# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

这是我创建的表格

{% extends 'base.html' %}

{% block contact %}
  <div class="contactProfile">
    <div class="container contact_form">
      <h3 class="title">Contact Us</h3>
      <p>Have questions or concern, please fill out the below inquiry form and a member of our team will contact you for assistance within 24 hours.</p>
      <!--Contact Us Page -->
      <form class="contact_info" action="" method="post" enctype="text/plain" action="index.html">
        {% csrf_token %}

        {% for field in form.visible_fields %}

        <div class="form-group">
          {{ field.errors }}

          <label>{{ field.label_tag }}</label>

          <p>{{ field }}</p>

          {% endfor %}

          <div class="input-group date" id="datetimepicker1" data-target-input="nearest">
            <div class="row align-items-start">
              <div class="col-md-6 date-selector">
                <label for="appt-date">Choose an appointment date: </label>
                <input type="date" class="form-control datetimepicker-input" data-target="#datetimepicker1" />
              </div>
              <div class="col-md-6 time-selector">
                <label for="appt-time">Choose appointment time: </label>
                <div class="time-slots">
                  <div class="row slot-selector">
                    {% for availableHr in availableHrs %}
                    <div class="col morning-appointment">
                      <a class="time-slots" href="{% url 'leonebraiding:booked-timeSlot' availableHr.id %}">{{availableHr.available_Time}}</a>
                      <!-- <a href="#" class="btn btn-outline-dark">{{availableHr.available_Time}}</a> -->
                      <!-- <a class="btn btn-outline-success" href="{% url 'leonebraiding:booked-timeSlot' availableHr.id %}">{{availableHr.available_Time}}</a> -->
                    </div>
                    {% endfor%}
                  </div>
                </div>
              </div>
            </div>

          </div>
          <br>



          <button type="submit" class="btn btn-outline-dark submit-button">Submit</button>
      </form>
    </div>
  </div>
{% endblock %}

这是我的看法

from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.urls import reverse
from .models import *
from .forms import ContactForm

# HOME PAGE VIEW
def homeView(request):
    carousel_item = FeaturedStyle.objects.all()
    registeredStyle = BraidStyle.objects.all()
    return render(request, 'index.html', {'styles': registeredStyle, 'featured_styles': carousel_item})


#ABOUT US PAGE VIEW
def aboutView(request):
    return render(request, 'about.html', {})


#GALLERY PAGE VIEW
def galleryView(request):
    gallery_post = GalleryPost.objects.all()
    return render(request, 'gallery.html', {'posts': gallery_post})


#APPOINTMENT PAGE VIEW
def pricingView(request):
    registeredPrice = HairstylePrice.objects.all()
    return render(request, 'pricing.html', {'haristyles': registeredPrice})


# CONTACT PAGE VIEW
def contactView(request):
    #available time
    time = AvailableAppointment.objects.all()
    #check for POST requests on load.
    form = ContactForm()

    if request.method == 'POST':
        form = ContactForm(request.POST or None)

        if form.is_valid():
            print("FORM IS VALID")
            print(form.cleaned_data)

    return render(request, 'contact.html', {'form': form, 'availableHrs': time})





def timeSlotView(request, timeSlot_id):
    booked_timeSlot = AvailableAppointment.objects.get(pk=timeSlot_id)
    booked_timeSlot.delete()

    return redirect('leonebraiding:contact')

    return render(request, 'booking.html', {})

这是我创建的表格

from django import forms
from datetime import datetime

class ContactForm(forms.Form):
    first_name = forms.CharField(max_length=20)
    last_name = forms.CharField(max_length=20)
    email_address = forms.EmailField(max_length=255)
    telephone_number = forms.CharField(max_length=10)
    message = forms.CharField(widget=forms.Textarea)

标签: django

解决方案


@VivekAnand 我使用引导程序重新创建了表单,然后在表单内添加了 {% csrf_token %} 标记。它现在按预期提交和发送电子邮件通知。见下文:

<form class="contact_info" action="" method="POST">
          {% csrf_token %}
          <div class="row g-3">
            <div class="col-sm-6">
              <label for="first-name">First Name</label>
              <input type="text" name="first-name" class="form-control" aria-label="First name" required>
            </div>
            <div class="col-sm-6">
              <label for="last-name">Last Name</label>
              <input type="text" name="last-name" class="form-control" aria-label="Last name" required>
            </div>
            <div class="col-sm-6">
              <label for="email">Email Address</label>
              <input type="email" name="email" class="form-control" aria-label="Email Address" required>
            </div>
            <div class="col-sm-6">
              <label for="tel">Phone Number</label>
              <input type="tel" name="phone" class="form-control"  id="phone-number" aria-label="Phone Number" required>
            </div>

            <div class="col">
              <label for="tel">Message</label>
              <textarea name="message" rows="4" cols="80" class="form-control" aria-label="Phone Number"></textarea>
            </div>
          </div>
          <br />

          <div class="input-group date" id="datetimepicker1" data-target-input="nearest">
            <div class="row align-items-start">
              <div class="col-md-6 date-selector">
                <label for="appt-date">Choose an appointment date: </label>
                <input type="date" name="date" class="form-control datetimepicker-input" data-target="#datetimepicker1" />
              </div>
              <div class="col-md-6 time-selector">
                <label for="appt-time">Choose appointment time: </label>
                <div class="time-slots" style="">
                  <div class="row slot-selector">
                    {% for availableHr in availableHrs %}
                    <a class="col btn btn-outline-dark" name="booked-time" id="timeSlot" href="{% url 'leonebraiding:booked-timeSlot' availableHr.id %}">{{availableHr.available_Time}}</a>
                    {% endfor%}
                  </div>
                </div>
              </div>
            </div>

          </div>

          <button type="submit" class="btn btn-outline-dark submit-button">Submit</button>
      </form>

推荐阅读