3

如果我正在使用我的views.py 看起来像这样的模型表单:

def dog_image_upload(request):
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = DogImageForm(request.POST, request.FILES)
            if form.is_valid():
                form.save()
        else:
            form = DogImageForm(user)
        return render_to_response("dog-image-upload.html", {'form': form}, context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect('/')

在model.py中我想这样做:

class DogImageForm(ModelForm):
    dogs = forms.ModelChoiceField(queryset=Dog.objects.filter(user=request.user))
    class Meta:
        model = ResultsUpload
        fields = ['dogs','image']

但是,我在尝试将用户发送到 model.py 时遇到了麻烦,这方面的帮助非常棒,值得一提!

4

1 回答 1

6

你必须在modelform的__init__

class DogImageForm(ModelForm):
    dogs = forms.ModelChoiceField(queryset=Dog.objects.none())
    class Meta:
        model = ResultsUpload

    def __init__(self, user, *args, **kwargs):
        super(DogImageForm, self).__init__(*args, **kwargs)
        self.fields['dogs'].queryset = Dog.objects.filter(user=user)

在表单初始化期间,

form = DogImageForm(user=request.user)
于 2013-07-21T02:47:54.333 回答