表单不接受额外参数
我试图向我的表单传递一个附加参数,这是一个对象到外键的关系。但不知道为什么表单返回 __init__() 得到了一个意外的关键字参数 'parent' 当我非常确定可以向表单的 __init__ 发送额外的参数时(即这里:简单表单未验证)。我错了吗?
def add_video(request):
parent = ParentObject.objects.all()[0]
if request.method == 'POST':
form = VideoForm(data=request.POST, parent=parent)
if form.is_valid():
form.save()
next = reverse('manage_playforward',)
return HttpResponseRedirect(next)
else:
form = VideoForm()
class VideoForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
try:
self.parent = kwargs.pop['parent']
logging.debug(self.parent)
except:
pass
super(VideoForm, self).__init__(*args, **kwargs)
I was trying to pass an additional parameter to my form, which is anObject to ForeignKey relation. But dunno why form returns __init__() got an unexpected keyword argument 'parent'
when I'm pretty sure that it is possible to send additional parameters to form's __init__
(ie here : Simple form not validating). Am I wrong ?
def add_video(request):
parent = ParentObject.objects.all()[0]
if request.method == 'POST':
form = VideoForm(data=request.POST, parent=parent)
if form.is_valid():
form.save()
next = reverse('manage_playforward',)
return HttpResponseRedirect(next)
else:
form = VideoForm()
class VideoForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
try:
self.parent = kwargs.pop['parent']
logging.debug(self.parent)
except:
pass
super(VideoForm, self).__init__(*args, **kwargs)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
kwargs.pop['parent']
抛出TypeError: 'builtin_function_or_method' object is unsubscriptable
,因为您尝试对函数方法进行键查找 ({}.pop
)。然后,该错误将被异常处理程序吞掉。为此,请执行
kwargs.pop('parent', None)
。对于您的情况:顺便说一句,99% 的情况下最好只捕获 except 块中的特定异常。这样做将有助于避免像这样的错误/混乱。另外,我强烈建议为这个自定义构造添加单元测试(或者只是 TDDing 你的其他代码,但这是一个单独的问题)
kwargs.pop['parent']
is throwingTypeError: 'builtin_function_or_method' object is unsubscriptable
, because you're trying to do a key lookup on a function method ({}.pop
). This error is then being swallowed by your exception handler.For this to work do
kwargs.pop('parent', None)
. In your case:As a side note, 99% of time its best to only catch specific Exceptions in your except blocks. Doing so will help dodge bugs/confusion like this. Also, I would highly suggest adding unit tests for this custom construction (or just TDDing your other code, but that's a separate issue)