2014-04-03 23 views
0

我一直在瀏覽API一段時間,我似乎無法弄清楚它是否有可能重寫某種save()方法在ModelForm中創建User上下文中目的在於將用戶添加到默認的特定組。使用CreateVIew默認添加用戶到組

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