我按照错误响应页面上的建议,但它仍然无法正常工作。这是我的代码;
views.py
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from forms import *
from models import *
def main_page(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
icecream = form.cleaned_data['icecream']
output = '''
<html>
<head>
<title>
Reading user data
</title>
</head>
<body>
<h1>
Your ice cream is: %s
</h1>
</body>
</html>''' %(
icecream
)
return HttpResponse(output)
else:
form = UserForm()
variables = RequestContext(request, { 'form': form})
return render_to_response( 'icecream.html', variables, context_instance=RequestContext (request))
icecream.html(模板)
<html>
<head>
<title>Getting user input</title>
</head>
<body>
<h1>Getting user input</h1>
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit"/>
</form>
</body>
</html>
urls.py
from django.conf.urls.defaults import *
from forms.views import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'^$', main_page),
settings.py(相关部分)
MIDDLEWARE_CLASSES = (
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
我正处于学习模式,所以这只是一个内部网站,我使用localhost访问它。我以前从未遇到过这个问题,我正在学习这本书的其他章节。这是我第一次使用表单和发布。我看过这个网站上的一些已回答的问题,但似乎没有任何帮助。感谢所有帮助。