0

我想要做的是使用 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

如果有人有解决此问题的解决方案,我将非常高兴!

4

1 回答 1

1

您将 request.POST 作为位置参数用户传递,request.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)
于 2013-07-21T04:17:36.110 回答