简体   繁体   中英

Validate objects in many-to-many relationship in Django

I have two models Group and User . I have a ManyToManyField in Group referencing User . I also have an intermediate model GroupUser storing additional data (date for assigning and type of membership) to the many-to-many relationship.

I have a page /groups/group-<group_id>/create-user/ at which I add users to the group. My problem is that if a user is created as type 1, he cannot be assigned to other groups. How can I validate that the user is not assigned to other groups if a relationship already exists with the specific user and type 1?

I'm using a CreateView

class GroupUserCreateView(CreateView):
    model = GroupUser
    fields = ['user', 'type']
    template_name = "group_user_create_form.html"

    def dispatch(self, request, *args, **kwargs):
        self.group = get_object_or_404(Group, id=self.kwargs['group_id'])
        return super(GroupUserCreateView, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        form.instance.group = self.group
        return super(GroupUserCreateView, self).form_valid(form)

    def get_success_url(self):
        return reverse('group_user_list', kwargs={'group_id': self.group.id})

Don't know much about CreateView, but my guess, overwrite get_form and adjust the queryset on the on the user field.

def get_form(self, form_class):
    create_form = super(GroupUserCreateView, self).get_form(form_class)
    create_form.fields['user'].queryset = User.objects.exclude(groupuser__type=1)
    return create_form

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM