我有一个显示表单并保存相同表单的视图。首次显示视图时,我没有错误。但是,在保存(POST)到视图时,我收到以下错误:
/ test6 / settings /的TypeError int()参数必须是字符串或数字,而不是'QueryDict'
查看
@login_required
def keyword_settings(request, keyword):
keyword = Keyword.objects.get(keyword=keyword, status="Active")
# If we had a POST then get the request post values.
if request.method == 'POST':
# Populate the form with the instance.
form = KeywordFrom(request.POST, instance=keyword)
# Check we have valid data before saving trying to save.
if form.is_valid():
form.save()
form = KeywordFrom(instance=keyword, user=request.user)
context = {'form': form}
return render_to_response('sms/keyword_settings.html', context, context_instance=RequestContext(request))
表格
class KeywordFrom(forms.ModelForm):
def __init__(self, user=None, *args, **kwargs):
"""
Init method.
"""
super(KeywordFrom, self).__init__(*args, **kwargs)
if user is not None:
this_originator_name = Originator.objects.for_user(user)
self.fields['sender_name'] = forms.ModelChoiceField(queryset=this_originator_name)
class Meta:
model = Keyword
我知道问题出在sender_name上,但我尝试了不同的事情而没有解决方法。
答案 0 :(得分:7)
看看你如何覆盖表单的__init__
方法:
def __init__(self, user=None, *args, **kwargs):
因此第一个显式参数(在隐式self
之后)是user
。
现在看一下如何在POST块中实例化表单:
form = KeywordFrom(request.POST, instance=keyword)
因此,您传递的第一个参数是POST。但是表格在该位置期待user
,并且会将您传递的任何内容放入该变量中。
您需要在POST实例化时传递用户,这将解决问题。但这表明为什么要乱用一个类的默认签名是个坏主意。您应该保留签名并从user
kwargs
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(KeywordFrom, self).__init__(*args, **kwargs)
...etc...