问题
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