1

我按照错误响应页面上的建议进行操作,但仍然无法正常工作。这是我的代码;

视图.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>

网址.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 访问它。我在学习这本书的其他章节之前从未遇到过这个问题。这是我第一次使用表单和发布。我在这个网站上查看了许多已回答的问题,但似乎没有任何帮助。感谢所有帮助。

4

0 回答 0