如何不使用AdminDjango将用户添加到不同的组

时间:2019-04-05 02:05:33

标签: django django-rest-framework

如何在不使用Admin的情况下将用户添加到不同的组,我了解我有三种类型的用户,他们可以在注册时选择他们想要的类型,我已经创建了具有不同权限的组,我问题是,当我通过车牌创建用户时,我还将他们添加到与之对应的组中?

到目前为止,这已得到证明:

views.py

class FreeSignUpView(CreateView):
    model=CustomUser
    form_class = FreeSignUpForm
    template_name = 'registration/signup_form.html'

    def  get_context_data(self, **kwargs):
        kwargs['user_type']='free'
        return super().get_context_data(**kwargs)

    def form_valid(self, form):
        user=form.save()
        login(self.request,user)
        return redirect('free_signup')

forms.py

class FreeSignUpForm(UserCreationForm):
    pais = forms.ModelChoiceField(queryset=Pais.objects.all())
    anno = forms.ModelChoiceField(queryset=Profesion.objects.all())

    class Meta(UserCreationForm.Meta):
        model=CustomUser
        fields = ('username','email','first_name','last_name',)

    def clean_email(self):
        email = self.cleaned_data.get('email')
        qs = CustomUser.objects.filter(email=email)
        if qs.exists():
            raise forms.ValidationError("La direccion email ya existe")
        return email


    @transaction.atomic()
    def save(self, commit=True):
        user=super().save(commit=False)
        user.is_free=True

      #the error occurs when I try to add the user to the group
        group=Group.objects.get(name='free')
        group.user_set.add(user)

        if commit:
            user.save()
        return user

,它引发了以下错误 enter image description here

1 个答案:

答案 0 :(得分:0)

最好的选择是创建一个Django signal,每当创建用户时,该用户便会将用户添加到组中。

def create_user_with_group(sender, instance, created, **kwargs):
    if created:
        instance.group = Group.objects.get(id=1) # replace this w/ however you add a user to your custom group
        instance.save()

post_save.connect(create_user_with_group, sender=User, dispatch_uid="create_user_with_group")
  

更多信息:https://simpleisbetterthancomplex.com/tutorial/2016/07/28/how-to-create-django-signals.html