Access request.user in modelForm

﹥>﹥吖頭↗ 提交于 2019-12-30 11:06:16

问题


If i am using model forms where my views.py looks like:

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('/')

And in model.py i want to do this:

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

However, i am having trouble trying to send the user to model.py Help on this would be awesome and point worthy!


回答1:


You would have to do it in the modelform's __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)

and during the initialization of the form,

form = DogImageForm(user=request.user)


来源:https://stackoverflow.com/questions/17768563/access-request-user-in-modelform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!