我想要做的是使用Django表单更新Dog模型中的现有行,但我遇到了错误。
我收到此错误:
__init__() got multiple values for keyword argument 'user'
因为django认为这里存在问题:
form = DogImageForm(request.POST, request.FILES, user=request.user, instance=instance)
我的model.py是
class DogImageForm(ModelForm):
dogs = forms.ModelChoiceField(queryset=Dog.objects.none())
class Meta:
model = Dog
fields = ['dogs','image']
def __init__(self, user, *args, **kwargs):
super(DogImageForm, self).__init__(*args, **kwargs)
userprofile = UserProfile.objects.get(user=user)
self.fields['dogs'].queryset = Dog.objects.filter(user=userprofile)
我的view.py是:
def dog_image_upload(request):
if request.user.is_authenticated():
if request.method == 'POST':
userprofile = UserProfile.objects.get(user=request.user)
instance = Dog.objects.get(id=str(request.POST['dogs']))#user=userprofile,
form = DogImageForm(request.POST, request.FILES, user=request.user, instance=instance)
if form.is_valid():
form.save()
reader = csv.reader(request.FILES['file'])
return HttpResponseRedirect('/members-dogs/')
else:
form = DogImageForm(user=request.user)
return render_to_response("dog-image-upload.html", {'form': form}, context_instance=RequestContext(request))
else:
return HttpResponseRedirect('/')
我最初坚持使用modelForm Access request.user in modelForm
传递request.user如果有人有解决方法来解决这个问题,我会非常高兴!
答案 0 :(得分:1)
您正在将request.POST作为位置参数user,request.user作为关键字参数user。你正在做以下事情:
>>> def f(user, *args, **kwargs): pass
...
>>> f('post', user='user')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() got multiple values for keyword argument 'user'
>>> f('user', 'post')
取而代之的是:
form = DogImageForm(request.user, request.POST, request.FILES, instance=instance)