I want to set a page to update a user information, including a field to create a new password. This page is strictly for updating existing user. The password field in this page will be optional.
There is another page with another view to create user where the password field is required there.
My current approach is to set the field required to be false in the view as below
class User(AbstractUser):
password = models.CharField(max_length=200)
# ommited the rest for brevity
class UserEdit(UpdateView):
model = User
fields = ['fullname', 'username','status','email','phone_number','role','program_studi','password']
template_name = 'user-management-edit.html'
success_url = reverse_lazy('user-management')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.initial['password'] = ''
self.fields['password'].required = False
def form_valid(self, form):
form.instance.edited_by = self.request.user
password = form.cleaned_data.get('password', None)
if password:
form.instance.set_password(password)
return super().form_valid(form)
{% for field in form %}
{% if field.name in inline_field %}
<div class="col-4">
{% if field.field.required %}
{% bootstrap_field field label_class='control-label required' %}
{% else %}
{% bootstrap_field field %}
{% endif %}
</div>
{% else %}
<div class="col-12 {% if field.name == 'radio_input' %} col-radio-input {% endif %}">
{% if field.field.required %}
{% bootstrap_field field label_class='control-label required' %}
{% else %}
{% bootstrap_field field %}
{% endif %}
</div>
{% endif %}
{% endfor %}
However, the line self.fields['password']
kept throwing TypeError list indices must be integers or slices, not str
which I have no idea why.
I tried to remove the required from the model itself like below
class User(AbstractUser):
password = models.CharField(max_length=200, blank=True, null=True)
but then I have no idea how to make the password field mandatory on the create user without throwing the same error.