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

时间:2014-04-03 18:21:08

标签: django

我已经查看了API一段时间了,我似乎无法弄清楚是否可以在save()创建的上下文中覆盖ModelForm中的某种User方法,用于将用户默认添加到特定组。

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')

1 个答案:

答案 0 :(得分:1)

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