gpt4 book ai didi

Django 过滤 ModelChoiceField 的查询集

转载 作者:行者123 更新时间:2023-12-02 05:51:02 25 4
gpt4 key购买 nike

我一直在使用一个名为 ModelChoiceField 的表单字段并通过所有对象进行查询,但这并不是我打算使用它的目的。

 class PictureForm(forms.ModelForm):
Whiteboard = forms.ModelChoiceField(queryset=Whiteboard.objects.all())

我一直在尝试使用 ModelChoiceField 来查询属于特定用户的所有 WhiteBoard 对象
Whiteboard = forms.ModelChoiceField(queryset=Whiteboard.objects.filter(user=request.user))

但我发现请求没有传递给 ModelForm 。我一直在通过 SO 搜索各种解决方案,一种解决方案是覆盖表单的 初始化 ()

这可能是与我的问题最接近的问题
How to use the request in a ModelForm in Django

这是他的解决方案。如果他的解决方案是覆盖 View 中的查询集。他如何在 forms.py 中创建没有查询集的 ModelChoiceField

就我而言,我想按用户过滤所有白板。我怎么能做到?

我的模块的一部分
class Whiteboard(models.Model):

Category =models.CharField(max_length=30,choices=CATEGORY)
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
picture = models.OneToOneField('Picture',related_name='picture',blank=True,null=True)
def __unicode__(self):
return self.name

class Picture(models.Model):
user = models.ForeignKey(User)
Whiteboard = models.ForeignKey(Whiteboard,blank=False,null=False,related_name='board')
image = models.FileField(upload_to="images/",blank=True)
description = models.TextField()
is_primary = models.BooleanField(default=False)

def __unicode__(self):
return self.description

我的观点.py
def PictureCreator(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))

if request.method == "POST":
form = PictureForm(request.POST , request.FILES)
if form.is_valid():
picture = Picture(user=request.user)
image = request.FILES.get('image')
if image:
picture.image = form.cleaned_data['image']
description = form.cleaned_data['description']
if description:
picture.description = form.cleaned_data['description']

if board:
picture.board = form.cleaned_data['board']
picture.save()
board = Whiteboard.objects.get(Whiteboard=picture.board)
the_id = board.id
return HttpResponseRedirect(reverse('world:Boat', kwargs={'animal_id': the_id }))

return render(request,'picture.html',{'form':PictureForm()})

图片.html
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type = "submit" value= "Add Picture" />
</form>

最佳答案

在类定义期间根本不要设置过滤器。您将在 View 中覆盖它。

form = PictureForm()
form.fields['whiteboard'].queryset = Whiteboard.objects.filter(user=request.user)

class PictureForm(ModelForm):
whiteboard = forms.ModelChoiceField(queryset=Whiteboard.objects.none(),)

关于Django 过滤 ModelChoiceField 的查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15608784/

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