如何将一个用户添加到多个组?

时间:2019-04-14 14:14:31

标签: django django-forms django-authentication

新手在这里。我正在创建一个项目managemnet应用程序,其中有一群老师的权限与学生不同(更高)。这些学生按4人一组排列,每个学生组都分配了一位老师。那么如何将一个用户添加到2个不同的组中?

为创建组,我将用户分别添加到一个新组中。 每个老师都将自己注册到老师组中 因此,在添加指导者时,我尝试通过其名称获取一个组并使用.user_set.add()

添加

models.py

from django.db import models, transaction
from django.db.models.signals import post_save
from django.contrib.auth.models import AbstractUser, Group

from phonenumber_field.modelfields import PhoneNumberField


class Domain(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name


class MyUser(AbstractUser):
    is_student      =   models.BooleanField(default=False)
    is_teacher      =   models.BooleanField(default=False)
    phonenumber     =   PhoneNumberField()


class Teacher(models.Model):
    user            =   models.OneToOneField(MyUser, on_delete=models.CASCADE, primary_key=True)
    domain          =   models.ManyToManyField(Domain, related_name='interested_domains')

    def __str__(self):
        return self.user.username


class Student(models.Model):
    user            =   models.OneToOneField(MyUser, on_delete=models.CASCADE, primary_key=True)
    division        =   models.CharField(max_length=4, blank=True)
    roll_no         =   models.IntegerField(blank=True)

    def __str__(self):
        return self.user.username


class GroupData(models.Model):
    group = models.OneToOneField(Group,on_delete=models.CASCADE,primary_key=True)
    domain = models.ManyToManyField(Domain,related_name='primary_domain')

    def __str__(self):
        return self.group.name

forms.py

class GroupCreateForm(forms.ModelForm):
    user1 = forms.ModelChoiceField(queryset=MyUser.objects.filter(is_student=True), empty_label="(Choose a User)")
    user2 = forms.ModelChoiceField(queryset=MyUser.objects.filter(is_student=True), empty_label="(Choose a User)")
    user3 = forms.ModelChoiceField(queryset=MyUser.objects.filter(is_student=True), empty_label="(Choose a User)")
    user4 = forms.ModelChoiceField(queryset=MyUser.objects.filter(is_student=True), empty_label="(Choose a User)")
    domain = forms.ModelChoiceField(
        queryset=Domain.objects.all(),
        required=True,
        empty_label="(Choose a Domain)"
    )
    class Meta:
        model = Group
        fields = ['name']

    def save(self):
        new_group, created = Group.objects.get_or_create(name=self.cleaned_data['name'])
        new_group.user_set.add(self.cleaned_data['user1'])
        new_group.user_set.add(self.cleaned_data['user2'])
        new_group.user_set.add(self.cleaned_data['user3'])
        new_group.user_set.add(self.cleaned_data['user4'])
        group=GroupData.objects.create(group=new_group)
        group.domain.add(self.cleaned_data.get('domain'))
        return new_group

class AddMentorForm(forms.Form):
    mentor = forms.ModelChoiceField(queryset=MyUser.objects.filter(is_teacher=True), empty_label="(Choose a User)")
    name  = forms.ModelChoiceField(queryset=Group.objects.all(),empty_label='(choose group)')

    def save(self):
        print(self.cleaned_data['name'])
        print(self.cleaned_data['mentor'])
        new_group,cleaned = Group.objects.get(name=self.cleaned_data['name'])
        new_group.user_set.add(self.cleaned_data['mentor'])
        return new_group

class TeacherForm(UserCreationForm):
    phone = PhoneNumberField(widget=PhoneNumberPrefixWidget(attrs={'placeholder': 'Cellphone', 'class': "form-control"}),
        label='Cellphone number',
        required=True,
        initial='+91')
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
    domain =  forms.ModelMultipleChoiceField(
        queryset=Domain.objects.all(),
        widget=forms.CheckboxSelectMultiple,
        required=True,
    )

    class Meta:
        model = MyUser
        fields = ('first_name', 'last_name', 'email')

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    @transaction.atomic
    def save(self,commit=True):
        user = super().save(commit=False)
        user.is_teacher = True
        user.is_active = False
        user.username,_ = self.cleaned_data['email'].split('@')
        user.first_name = self.cleaned_data['first_name']
        user.last_name  = self.cleaned_data['last_name']
        user.phonenumber = self.cleaned_data['phone']
        user.set_password(self.cleaned_data["password1"])
        user.save()
        new_group, created = Group.objects.get_or_create(name='teachers')
        new_group.user_set.add(user)
        teacher = Teacher.objects.create(user=user)
        teacher.domain.add(*self.cleaned_data.get('domain'))
        return user

views.py


class GroupCreateView(CreateView):
    form_class = GroupCreateForm
    template_name = './profiles/form.html'
    success_url = reverse_lazy('home')

class TeacherSignUpView(CreateView):
    form_class = TeacherForm
    template_name = 'profiles/form.html'
    model = Teacher

    def get_context_data(self, **kwargs):
        kwargs['user-type'] = 'teacher'
        return super().get_context_data(**kwargs)

    def form_valid(self, form):
        user = form.save()
        current_site = get_current_site(self.request)
        subject = 'Activate POMAS account'
        message = render_to_string('./profiles/account_activation_email.html', {
            'user': user,
            'domain': current_site.domain,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
            'token': account_activation_token.make_token(user),
        })
        user.email_user(subject, message)
        print(user.email_user(subject, message))
        return redirect('account_activation_sent')

class AddMentorView(FormView):
    template_name = './profiles/form.html'
    form_class = AddMentorForm
    success_url = reverse_lazy('home')

    def form_valid(self, form):
        print(self.request.user.groups.all())
        req=form.save()
        return redirect('home')

实际结果: Teacher1 => ['teachers'] //小组

预期结果: Teacher1 => ['teachers','grp1','grp2',...] //组

0 个答案:

没有答案