我尝试将输入文本从index.html发送到我的查看功能,即"结果"。 当我点击“生成摘要”时,按钮显示csrf验证失败。缺少CGrf令牌。需要紧急帮助。
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from .models import Input
from django.views.decorators.csrf import csrf_protect
def home(request):
input=Input.objects.all()
template=loader.get_template('home/index.html')
context={
'input':input,
}
return HttpResponse(template.render(context,request))
def result(request,input_text):
Input.input_text = request.POST('input_text')
return HttpResponse("<h1> text is"+Input.input_text)
的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
{% load staticfiles %}
<link rel='stylesheet'href="{% static 'css/bootstrap.min.css' %}" type='text/css'/>
</head>
<body background="/static/home/img/bg.jpg">
<center><h1> <font color="white" >Summarizeit.com !</h1></center>
<form name="myform" action="." method="post">{% csrf_token %}
<div class="form-group">
<center><label for="abc">Input Text</label>
<input type="text" name="input_text"class="form-group" id="abc"placeholder="Text input">
</div>
<br><br>
<center><button type="submit" class="btn btn-default"> Generate Summary !</button>
</form>
</body>
</html>
家/ urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
]
finalproject / urls.py(根项目)
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', include('home.urls'))
]
models.py
from django.db import models
class Input(models.Model):
input_text = models.CharField(max_length=250)
def __str__(self):
return self.input_text
Settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y)m04wnmm%i_#uih%^j5&aqeozlp!gt#px&z!*uf=-%v98x#-i'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'home',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'finalproject.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 = 'finalproject.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
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',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
答案 0 :(得分:1)
出于某种原因,你正在以艰难的方式渲染模板,这绕过了Django为你做的所有自动操作:最重要的是,运行包含CSRF令牌的上下文处理器。
您的观点应为:
def home(request):
input=Input.objects.all()
context={
'input':input,
}
return render(request, 'home/index.html', context)
另请注意,您在结果视图中设置Input.input_text
根本没有意义;你需要创建一个Input实例,设置它的input_text,然后保存它。