目前在Django工作并尝试对表单进行简单的教程,但是在提交表单时收到错误。
这是我的urls.py:
from .views import*
urlpatterns = [
url(r'^name/', get_name, name='TheName'),
url(r'^name/present/', present, name='Present'),
]
以下是观点:
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
return HttpResponseRedirect
else:
form = NameForm()
return render(request, 'home/name.html', {'form': form})
def present(request):
return render(request, 'home/present.html')
以下是表格:
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
这是name.html:
<form action="present/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
这是我的present.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ your_name }}</title>
</head>
<body>
</body>
</html>
单击提交后,以及带有回溯的错误消息:
Environment:
Request Method: POST
Request URL: http://localhost:8000/name/present/
Django Version: 1.11.4
Python Version: 3.6.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed 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']
Traceback:
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/deprecation.py" in __call__
142. response = self.process_response(request, response)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/middleware/clickjacking.py" in process_response
32. if response.get('X-Frame-Options') is not None:
Exception Type: TypeError at /name/present/
Exception Value: get() missing 1 required positional argument: 'header'
任何帮助将不胜感激!
答案 0 :(得分:5)
成功提交表单后,您需要告诉重定向的位置。您只是return HttpResponseRedirect
这是无效的,而应该是:
return HttpResponseRedirect(the_path_to_redirect_to)
请阅读有关HttpResponseRedirect的文档。