I would like to use a custom form field with an UpdateView. My code so far is:
models.py
class CustomUser(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
paper = models.BooleanField(default=False)
pronouns = models.CharField(max_length=50, blank=True)
def __str__(self):
return self.username
forms.py
class CustomUserProfileForm(forms.ModelForm):
pronouns = forms.CharField(label='Pronouns', required=True)
class Meta:
model = get_user_model()
fields = ('first_name', 'last_name')
def __init__(self, *args, **kwargs):
_pronoun_list = ('he/him/his', 'she/her/hers', 'they/them/theirs')
super(CustomUserProfileForm, self).__init__(*args, **kwargs)
self.fields['pronouns'].widget = ListTextWidget(
data_list=_pronoun_list, name='pronoun-list')
This form references ListTextWidget although I don't think it directly relates to my issue:
class ListTextWidget(forms.TextInput):
def __init__(self, data_list, name, *args, **kwargs):
super(ListTextWidget, self).__init__(*args, **kwargs)
self._name = name
self._list = data_list
self.attrs.update({'list': 'list__%s' % self._name})
def render(self, name, value, attrs=None, renderer=None):
text_html = super(ListTextWidget, self).render(
name, value, attrs=attrs)
data_list = '<datalist id="list__%s">' % self._name
for item in self._list:
data_list += '<option value="%s">' % item
data_list += '</datalist>'
return (text_html + data_list)
Views.py
class CustomUserProfileview(UpdateView):
model = CustomUser
form_class = CustomUserProfileForm
template_name = 'account/customuser_change_form.html'
success_url = reverse_lazy('home')
def form_valid(self, form):
user = self.request.user
pronouns = form.cleaned_data['pronouns']
user.pronouns = pronouns
user.save()
return super().form_valid(form)
The form is displayed as I would expect, where I can change the first name, last name and choose pronouns from a list. If I print(user) and print(pronouns) I get my expected results, but the pronouns field is not being saved to the user. Even if it did save, I get the feeling that I'm not leveraging the UpdateView correctly.