django表单从查询集中排除用户实例

时间:2013-02-12 15:10:48

标签: python django django-forms django-formwizard

我有以下型号:

类UserProfile(models.Model):

user = models.OneToOneField(User, related_name="user")
people_interested = models.ManyToManyField(User, related_name="interested")

现在我想要一个表单,我想为用户提供一个表单,他们可以选择people_interested,所以我添加以下forms.py

class ChooseForm(forms.Form):
    q_set = User.objects.all()
    peers = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset = q_set)

然后在视图中:

form = ChooseForm(data = request.POST or None)
if request.POST and form.is_valid():
    uprofile, created = UserProfile.objects.get_or_create(user=request.user)
    uprofile.people_interested = form.cleaned_data['peers']
    uprofile.save()
    return HttpResponseRedirect("/")
else:
    return render(request, "form_polls.html", {'form':form})

但问题是,当前的用户实例也会显示出来。所以我在views.py中尝试了以下内容:

form = ChooseForm(request.user.id, data = request.POST or None)

然后在forms.py

class ChooseForm(forms.Form):

    def __init__(self, uid, *args, **kwargs):
        super(ChooseForm, self).__init__(*args, **kwargs)
        self.fields['peers'].queryset = User.objects.exclude(id=uid)
    q_set = User.objects.all() 
    peers = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset = q_set)

但上面不是一个干净的实现,有没有更好的方法呢?

2 个答案:

答案 0 :(得分:2)

是什么让你说这不是一个干净的实现?在queryset上覆盖__init__是完全可以接受的。

我改进代码的唯一方法是在post_save上使用User信号创建UserProfile,然后在您的视图上执行user.get_profile()。见this question

您还可以使用ModelForm代替UserProfile代替常规表单,并将字段限制为people_interested

答案 1 :(得分:1)

模型

class Leave(TimeStamp):
    """
    Model : Leave Model

    """
    id          = models.UUIDField(primary_key=True, default=token, editable=False,unique=True)
    owner       = models.ForeignKey(Profile,on_delete=models.CASCADE,related_name='leaves')
    start_date  = models.DateField(null=False,blank=False)
    end_date    = models.DateField(null=False,blank=False)
    leave_type  = models.CharField(choices=LEAVE_TYPE,max_length=30,default=SICK,null=True,blank=False)
    reason      = models.TextField(max_length=250,null=False,blank=False)
    duty        = models.TextField(max_length=600,null=False,blank=False)
    status      = models.CharField(max_length=12,default=PENDING)

    # admin fields only
    is_approved = models.BooleanField(default=False)
    approved_by = models.ForeignKey(User,on_delete=models.PROTECT,related_name='to_approve_leaves',null=True,blank=True)
    approved_on = models.DateTimeField(null=True,blank=True)

    is_accepted = models.BooleanField(default=False)
    accepted_by = models.ForeignKey(User,on_delete=models.SET_NULL,null=True,blank=False,related_name='leaves_to')
    report_to   = models.CharField(max_length=250,blank=True,null=True)

我需要一个表格来列出所有排除登录用户的用户 * accepted_by->在所有用户的下拉列表中不得包含登录用户

在我的 forms.py

class LeaveCreateForm(forms.ModelForm):

    def __init__(self,user_id,*args,**kwargs):
        super(LeaveCreateForm,self).__init__(*args,**kwargs)
        self.fields['accepted_by'].queryset = User.objects.exclude(id = user_id.id)#exclude login user in drop-down user list
    qryset = User.objects.all()
    (check here -> ) accepted_by = forms.ModelChoiceField(queryset=qryset,label="Assign work to",help_text='',required=True)

leave_type = forms.ChoiceField(choices=LEAVE_TYPE,initial=SICK,widget=forms.RadioSelect())