Django 形式“恰好需要 1 个参数(给定 2 个参数)”错误 - 可能与 CSRF 有关?
我正在 Django 1.3 上尝试一个相当简单的表单,并试图了解 CSRF 的工作原理。
我想我已经遵循了 Django 网站上详细介绍的三个步骤 ,但我仍然无法使表格工作。
加载 URL 时会显示表单,但是点击提交按钮后,出现以下错误:
/txt/ txt() 处的 TypeError 恰好需要 1 个参数(给出 2 个)
这是实际的代码:
views.py:
from django.http import HttpResponse
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
def txt(request):
if request.method == 'POST':
msg="txt received"
else:
msg="nothing in POST"
return render_to_response('base.html', locals(), context_instance=RequestContext(request))
HTML:
<body>
<form action="txt/" method="POST">{% csrf_token %}
From <input type="text" name="From"><br>
To <input type="text" name="To"><br>
Body <input type="text" name="Body"><br>
<input type="submit" value="Search">
</form>
{{ msg }}
</body>
我知道我还没有完成 forms.py 等,但我只是想启动并运行基本功能。我认为这段代码在以前版本的 Django 中可以工作,但不确定为什么这次不起作用。
I am attempting a fairly simple form on Django 1.3, and am trying to understand how CSRF works.
I think I've followed the three steps detailed on the Django site, but am still unable to make the form work.
The form displays when the URL is loaded, however upon hitting the submit button, I get the following error:
TypeError at /txt/ txt() takes exactly
1 argument (2 given)
Here's the actual code:
views.py:
from django.http import HttpResponse
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
def txt(request):
if request.method == 'POST':
msg="txt received"
else:
msg="nothing in POST"
return render_to_response('base.html', locals(), context_instance=RequestContext(request))
The HTML:
<body>
<form action="txt/" method="POST">{% csrf_token %}
From <input type="text" name="From"><br>
To <input type="text" name="To"><br>
Body <input type="text" name="Body"><br>
<input type="submit" value="Search">
</form>
{{ msg }}
</body>
I know I haven't done a forms.py etc. but I was just trying to get the basic functionality up and going. I think this code would have worked in previous versions of Django, and am unsure why its not working this time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该错误看起来像是您的视图函数获取的参数多于它设置接受的参数。正如上面所示,该视图只接受一个参数:请求。
如果此视图的 URL 模式配置有捕获组,或者您通过 可选字典 或 kwargs 参数传递给 url(),那么这些额外的参数将被传递给视图函数,并可能导致您看到的错误。
The error looks like your view function is getting more arguments than it is setup to accept. As you have it shown above, the view only accepts a single argument: the request.
If your URL pattern for this view is configured with a capturing group, or you are adding extra arguments via the optional dictionary or the kwargs parameter to url(), then those extra arguments will be given to the view function and could cause the error you're seeing.