0
我想要做的是使用Django窗體更新Dog模型中的現有行,但我遇到了一個錯誤。ModelForm不喜歡接收實例
我收到此錯誤:
__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!
感謝@falsetru奏效! –
@AlexStewart,不客氣。我多次犯了這個錯誤;) – falsetru