gpt4 book ai didi

python - 在modelForm中访问request.user

转载 作者:行者123 更新时间:2023-11-28 21:23:15 26 4
gpt4 key购买 nike

如果我正在使用我的 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 时遇到了问题在这方面的帮助会很棒并且值得一提!

最佳答案

您必须在模型的 __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)

关于python - 在modelForm中访问request.user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17768563/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com