我正在尝试将request.user放入ModelForm中。我觉得我已经尝试了所有这些因为重载
的排列__init__
参数(每Django form, request.post and initial)尝试将其作为kwargs传递(per Django form __init__() got multiple values for keyword argument)。我
似乎kwargs似乎是最好的方法,但我完全被它阻止了。
这是ModelForm:
class DistListForm(ModelForm):
members = ModelMultipleChoiceField(queryset=Company.objects.none())
class Meta:
model = DistList
fields = ['name', 'description', 'members', 'is_private']
def __init__(self, *args, **kwargs):
super(DistListForm, self).__init__(*args, **kwargs)
user = kwargs.pop('user', None)
up = UserProfile.objects.get(user=user)
/.. etc ../
以下是创建功能目前的工作原理:
def distlistcreate(request):
user = {'user': request.user}
form = DistListForm(**user)
if request.method == 'POST':
form = DistListForm(request.POST)
if form.is_valid():
distlist = form.save(commit=False)
distlist.creator = request.user
distlist.save()
form.save_m2m()
return HttpResponseRedirect(reverse('distlistsmy'))
return render(request, 'distlistcreate.html',{'form':form})
抛出TypeError的: init ()得到一个意外的关键字参数'user'。更新方法同样无益:
def distlistupdate(request, object_id):
distlist = get_object_or_404(DistList, id=object_id)
form = DistListForm(user=request.user, instance=distlist)
if request.method == 'POST':
form = DistListForm(request.POST, user=request.user)
它也会抛出相同的错误。
我现在已经在这堵墙上撞了两个小时了。将关键字参数传递给ModelForm的正确方法是什么?
这是Django 1.6.1,如果这有所不同。
答案 0 :(得分:4)
你必须在调用super()之前弹出用户参数,这样才不会与ModelForm的默认参数冲突
class DistListForm(ModelForm):
members = ModelMultipleChoiceField(queryset=Company.objects.none())
class Meta:
model = DistList
fields = ['name', 'description', 'members', 'is_private']
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(DistListForm, self).__init__(*args, **kwargs)
user_profile = UserProfile.objects.get(user=user)
答案 1 :(得分:0)
昨天刚刚在Django 1.5上完成了这个,我能够做到:
def __init__(self, user, *args, **kwargs):
在我的ModelForm上。然后我只使用用户而不必从kwargs中弹出它。