My form.py:
class CreateUserForm(HelperForm):
USER_TYPE_CHOICES = (
(False, 'Employee'),
(True, 'Admin'),
)
first_name = forms.CharField(
label="First Name",
max_length=30,
required=True,
validators=[firstNameValidator]
)
last_name = forms.CharField(
label="Last Name",
max_length=30,
required=True,
validators=[lastNameValidator]
)
email = forms.EmailField(
label="Email",
required=True,
validators=[emailValidator]
)
job_role = forms.ModelChoiceField(required=True, queryset=Group.objects.all(), initial=0)
is_superuser = forms.ChoiceField(label='User Type', choices=USER_TYPE_CHOICES)
is_active = forms.BooleanField(initial=False, required=False, widget=forms.HiddenInput())
class Meta:
model = User
fields = ('first_name', 'last_name', 'username',
'email', 'job_role', 'is_superuser', 'is_active')
What’s the initial=0
for? Get rid of it. And also after submitting the form, check in the db if the job_role
has been saved. If it’s in the db and the rest is correct, it should show up in the form.
I have done what you said but it is not showing which I selected at the time of user creation, look at picture,
Thanks
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()
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 post(self, request, *args, **kwargs):
form_data = self.get_form_kwargs()['data']
job_role_id = form_data.get('job_role', 0)
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)