我想要做的是使用 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 传递 request.user在这里访问 modelForm 中的 request.user
如果有人有解决此问题的解决方案,我将非常高兴!