Django 默认情况下,使用CreateVIew将用户添加到组

Django 默认情况下,使用CreateVIew将用户添加到组,django,Django,我已经浏览API有一段时间了,我似乎不知道是否可以在User创建的上下文中重写ModelForm中的某种save()方法,以便根据默认值将用户添加到特定组中 views.py: class PatientCreate(LoginRequiredMixin, GroupRequiredMixin, CreateView): template_name = "adminApp/patient/patient_create.html" model = User form_cla

我已经浏览API有一段时间了,我似乎不知道是否可以在
User
创建的上下文中重写ModelForm中的某种
save()
方法,以便根据默认值将用户添加到特定组中

views.py:

class PatientCreate(LoginRequiredMixin, GroupRequiredMixin, CreateView):
    template_name = "adminApp/patient/patient_create.html"
    model = User
    form_class = MyPatientCreateForm
    group_required = u'Therapist'
    success_url = reverse_lazy('admin_patient_list')
forms.py:

class MyPatientCreateForm(ModelForm):
    first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
    last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
    username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
    email = forms.EmailField(widget=forms.TextInput(attrs={'class':'form-control'}))    
    password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control','placeholder':'Password'}))
    class Meta:
        model = User
        fields = ('username', 'email', 'password')
class PatientCreate(LoginRequiredMixin, GroupRequiredMixin, CreateView):

    # ...

    def form_valid(self, form):
        response = super(PatientCreate, self).form_valid(form)  # self.object gets saved here, and the response is a `HttpResponseRedirect`
        self.object.groups.add(the_group)  # add self.object to the group
        return response  # don't forget to return the response