python - Validate objects in many-to-many relationship in Django -
i have 2 models group
, user
. have manytomanyfield in group
referencing user
. have intermediate model groupuser
storing additional data (date assigning , type of membership) many-to-many relationship.
i have page /groups/group-<group_id>/create-user/
@ add users group. problem if user created type 1, cannot assigned other groups. how can validate user not assigned other groups if relationship exists specific user , type 1?
i'm using 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 createview, guess, overwrite get_form
, adjust queryset on on 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
Comments
Post a Comment