Django中的KeyError形式为kwargs

时间:2017-04-08 11:00:17

标签: django

def user_info(request, template_name='social/retrieve_user_data.html', username=None):
    user = User.objects.get(username=username)
    if request.method == 'POST':
        form = UserInfoForm(request.POST, user)
        print(form.is_valid())
        if form.is_valid():
            form.save()
    else:
        print('not post')
        form = UserInfoForm(user)


    return render_to_response(template_name, RequestContext(request, {
        'form': form,
    }))


class UserInfoForm(forms.Form):


    def __init__(self,*args,**kwargs):
        self.user = kwargs.pop('user')
        super(UserInfoForm,self).__init__(*args,**kwargs)

这产生了一个KeyError,异常值为u' user'。这有什么不对?在这两种情况下,使用有效的user值初始化表单。我为什么得到一个keyerror>

2 个答案:

答案 0 :(得分:4)

您未在if或else块中将用户作为关键字参数传递。它应该是:

form = UserInfoForm(request.POST, user=user)

form = UserInfoForm(user=user)

答案 1 :(得分:0)

只有func(foo=bar)才能将{"foo":bar}放入kwargs字典中!根据您的代码form = UserInfoForm(request.POST, user),您可以使用self.user = args[1]来捕获user