Python错误:视图form.formapp.views.contact未返回HttpResponse对象。解决方法
我刚开始学Python,现在在用视图和网址处理一个表单……我的项目叫做 projec1,而我的应用程序叫 usersapp。
这是我的 **usersapp/views.py** 文件。
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from users.form import ContactForm
def contact(request):
if request.method == "POST":
contact_form = ContactForm(request.POST)
if contact_form.is_valid():
success = True
username = contact_form.cleaned_data['username']
password = contact_form.cleaned_data['password']
else:
contact_form = ContactForm()
return render_to_response('contact.html', {'contact_form': contact_form})
这是我的 usersapp/contact.html 文件。
{%block title%}
Contact
{%endblock%}
{%block content%}
<h2>Contact</h2>
<form action ='.' method = 'POST'>
{{contact_form.as_p}}
<input type ="Submit" name = "submit" value = "send">
</form>
{%endblock%}
这是我的 usersapp/form.py 文件。
from django import forms
class ContactForm(forms.Form):
username = forms.CharField()
password = forms.CharField()
这是我的 projec1/urls.py 文件。
from django.conf.urls import patterns, include, url
from django.conf.urls.defaults import *
from users.views import login
from users.views import contact
urlpatterns = patterns('',
('^contact/$', contact),
)
我遇到了这个错误。
TypeError at /
Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given)
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.4.3
Exception Type: TypeError
Exception Value:
Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given)
我的错误是:
NameError at /contact
name 'forms' is not defined
Request Method: GET
Request URL: http://127.0.0.1:8000/contact
Django Version: 1.4.3
Exception Type: NameError
Exception Value:
name 'forms' is not defined
Exception Location: C:\Users\Documents\MyProjects\projec1\users\form.py
in<module>,line 2
Python Executable: C:\Python27\python.exe
请有人指导一下我,谢谢你们!
1 个回答
1
表单类的定义是错误的,这可能导致了那个错误:
from django import forms
# Inherit from `forms.Form`, not from `forms`:
class ContactForm(forms.Form):
username = forms.CharField()
password = forms.CharField()
在视图函数中也有几个问题:
def contact(request):
if request.method == "POST":
contact_form = ContactForm(request.POST)
# Not `contact_form is valid()`:
if contact_form.is_valid():
success = True
# `cleaned_data` is all lowercase:
username = contact_form.cleaned_data['username']
password = contact_form.cleaned_data['password']
else:
contact_form = ContactForm()
# You always want to return a response. Putting the return statement
# here will fix the error mentioned in the question's title. The
# second argument makes `contact_form` available from the template:
return render_to_response('contact.html', {
'contact_form': contact_form
})