my form.py:
class EditUserForm(HelperForm):
job_role = forms.ModelChoiceField(queryset=Group.objects.all(), required=True)
USER_TYPE_CHOICES = (
(False, 'Employee'),
(True, 'Admin'),
)
is_superuser = forms.ChoiceField(label='User Type', choices=USER_TYPE_CHOICES)
class Meta:
model = User
fields = [
'first_name', 'last_name', 'username', 'email', 'is_superuser', 'job_role'
]
def __init__(self, *args, **kwargs):
super(EditUserForm, self).__init__(*args, **kwargs)
# self.fields['job_role'].initial = self.instance.groups.all() # want to get selected job_role
def save(self, commit=True):
user = super(EditUserForm, self).save(commit)
user.save()
user.groups.clear()
user.groups.add(self.cleaned_data.get('job_role'))
return user
my views.py:
class UserEdit(PermissionRequiredMixin, AjaxUpdateView):
model = User
form_class = EditUserForm
context_object_name = 'user'
ajax_template_name = 'modal_form.html'
ajax_form_title = 'Edit User'
permission_required = ('users.edit_users',)
def get_data(self):
return {
'info': 'Edited user information',
}
def get_initial(self):
initial = super(UserEdit, self).get_initial()
try:
job_role = self.get_object().job_role
except:
pass
else:
initial['job_role'] = job_role.pk
return initial
def post(self, request, *args, **kwargs):
form_data = self.get_form_kwargs()['data']
job_role_id = form_data.get('job_role')
job_role_id = 0 if job_role_id == '' else job_role_id
job_role = Group.objects.filter(id=int(job_role_id)).first()
user = self.get_object()
if job_role:
user.groups.add(job_role)
return super(UserEdit, self).post(request, args, kwargs)