在ModelForm字段中过滤模型实例

时间:2015-07-12 15:47:13

标签: django django-models django-forms django-queryset modelform

如果在另一个问题中已经涉及到这一点,我深表歉意 - 我是Django的新手,并且可能一直盯着这个以及Stack上的许多其他问题,现在有点太长了。

使用Django 1.8.2,我有一个显示用户列表的模型,我想从中排除当前用户(即你不能看到自己)。我试图通过覆盖 init 方法来从" to_user"中排除当前用户。名单。我收到以下错误("邀请没有to_user"),我不明白。不应该从模型中的to_user ForeignKey字段填充该字段吗?

非常感谢您的帮助和时间 -

具体错误是:

enter image description here

我的型号是:

class Invitation(models.Model):
    from_user = models.ForeignKey(User, related_name="invitations_sent")
    to_user = models.ForeignKey(User, related_name="invitations_received", verbose_name="User to Invite", help_text="This is Help Text") # Verbose name is the form label for Foreigh Key vars
    message = models.CharField("Optional Message", max_length=300, blank=True) # Can add string for lavel, Setting blank=True means the field won't be required with ModelForm
    timestamp = models.DateTimeField(auto_now_add=True)

我的表单类是:

class InvitationForm(ModelForm):
    class Meta: # Class Meta sets the model class that the form needs to be auto-created for
        model = Invitation
        exclude = ['from_user']

    def __init__(self, user, **kwargs):
        super(InvitationForm, self).__init__(user, **kwargs)
        self.fields['to_user'].queryset = Invitation.objects.exclude(user=self.instance.to_user)

我的视图是:

@login_required
def new_invitation(request):
    if request.method == "POST":
        invitation = Invitation(from_user=request.user)
        form = InvitationForm(data=request.POST, instance=invitation)
        if form.is_valid():
            form.save()
        return redirect('user_home')
    else:
        form = InvitationForm(user=request.user)
    return render(request, "tictactoe/new_invitation.html", {'form' : form})

2 个答案:

答案 0 :(得分:1)

目前尚不清楚为何更改了__init__方法的签名。您不应该将用户转到super()来电。由于您没有在任何地方使用user,并且在实例化表单时没有传递它,我会将其删除。

其次,您可能希望排除instance.from_user而不是instance.to_user

class InvitationForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(InvitationForm, self).__init__(*args, **kwargs)
        self.fields['to_user'].queryset = Invitation.objects.exclude(user=self.instance.from_user)

答案 1 :(得分:1)

我的问题是尝试从邀请模型构建一个查询集,该模型集不包含我想要过滤的内容。根据Alasdair的建议,关键是将User模型导入我的forms.py文件,然后在User模型上构建查询集,从视图中传入登录用户。

我的 ModelForm 现在看起来像:

class InvitationForm(ModelForm):

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(InvitationForm, self).__init__(*args, **kwargs)
        self.fields['to_user'].queryset = User.objects.exclude(id=user.id)

    class Meta:
        model = Invitation
        exclude = ['from_user']

查看

实例化
@login_required
def new_invitation(request):
    if request.method == "POST":
        invitation = Invitation(from_user=request.user)
        form = InvitationForm(user=request.user, data=request.POST, instance=invitation)
        if form.is_valid():
            form.save()
            return redirect('user_home')
    else:
        form = InvitationForm(user=request.user)
    return render(request, "tictactoe/new_invitation.html", {'form' : form})

谢谢大家的帮助。