Django过滤ModelChoiceField的查询 [英] Django filter the queryset of ModelChoiceField

查看:122
本文介绍了Django过滤ModelChoiceField的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm been using a form field called ModelChoiceField and querying by all the objects but it's not extactly what I intended to use it for.

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

我一直在尝试使用ModelChoiceField查询属于特定用户的所有WhiteBoard对象

I'm been trying to use the ModelChoiceField to query for all the WhiteBoard objects that belong to a particular user

Whiteboard = forms.ModelChoiceField(queryset=Whiteboard.objects.filter(user=request.user))

但是我发现请求不会传递给ModelForm。我一直在通过SO搜索各种解决方案,一个解决方案是覆盖窗体的 init ()

but I discovered that the request does not pass to the ModelForm .I'm been searching through SO for various solution and one solution was to override the forms's init()

这可能是与我的问题相关的最接近的问题
如何使用请求Django中的ModelForm

This is probably the closest question that relate to my problem How to use the request in a ModelForm in Django

这是他的解决方案。如果他的解决方案是在视图中覆盖查询集。如何在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

我的views.py

My views.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()})

picture.html

picture.html

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


推荐答案

通过用户 init 中,然后在视图中您的窗体中必须传递用户值 PictureForm(request.user)

Pass user in init then in your form in the view you must pass the user value PictureForm(request.user)

class PictureForm(forms.ModelForm):
    class Meta:
        model = Picture

    def __init__(self, user, *args, **kwargs):
        super(PictureForm, self).__init__(*args, **kwargs)
        self.fields['Whiteboard'].queryset = Whiteboard.objects.filter(user=user)


def PictureCreator(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('world:LoginRequest'))

    if request.method == "POST":
        form = PictureForm(request.user, 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(request.user)})

这篇关于Django过滤ModelChoiceField的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆