如果我正在使用我的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时遇到问题 对此的帮助将是非常棒的,值得一试!
答案 0 :(得分:6)
您必须在模型中使用__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)