防止项目的创建者成为项目的成员

时间:2013-03-05 20:24:48

标签: django django-models django-forms django-views

当您在应用程序中创建项目时,我正在处理它可以选择哪些用户应该成为项目的成员。但是,我不希望项目的创建者(作为管理员)位于您可以选择成为成员的用户列表中。

您是管理员或成员,而不是两者。当然可以不添加一个自我作为成员,但我甚至不希望它成为可能。

怎么可以这样做?

查看:

def project_add(request):
if request.method == "POST":
    form = ProjectForm(request.POST)
    if form.is_valid():
        form.instance.date_added = datetime.date.today()
        form.instance.date_updated = datetime.date.today()
        form.instance.added_by_user = request.user
        form.save()
        return redirect(project_list)
else:
    form = ProjectForm()

return render(request, 'projects/add.html', {"form" : form})

项目模型:

class Project(models.Model):
...rest of the fields...
added_by_user = models.ForeignKey(User)
users = models.ManyToManyField(User, related_name='projects')

def __unicode__(self):
    return self.name

def owned_by_user(self, user):
    return self.added_by_user == user

表单:

class ProjectForm(ModelForm):
class Meta:
    model = Project
    exclude = ('date_added', 'date_updated', 'added_by_user')

...

为了更清楚,我在下面提供了一张图片。我不希望“Nisse”可以在下面的“Users:”下面选择(这是项目的成员),因为Nisse是创建项目的用户。

1 个答案:

答案 0 :(得分:2)

试试这个:

class ProjectForm(ModelForm): 
    ...
    users = forms.ModelMultipleChoiceField(queryset=User.objects.all())

    # change the queryset for the modelform `users` field to exclude `instance.added_by_user`
    def __init__(self, *args, **kwargs):
        super(ProjectForm, self).__init__(self, *args, **kwargs)
        if self.instance:
            self.fields['users'].queryset = self.fields['users'].queryset.exclude(self.instance.added_by_user)

    # custom clean method to not allow the `added_by_user`
    def clean(self):
        cleaned_data = super(ProjectForm, self).clean()
        if self.instance.added_by_user in cleaned_data.get('users'):
            raise ValidationError("OH NOES")
        return cleaned_data

你可能需要按摩一下。它未经测试但你明白了

https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-clean-method