I went ahead and created a Form to update the user database entry.
class UserUpdateForm(forms.ModelForm):
class Meta:
model = User
fields = ("username", "first_name", "last_name", "email")
But when I render the form all input fields are empty. How do I populate them with the user's data like current username and email?
I use Bootstrap 5 to style it, but that should matter:
<div >
<label for="{{ form.first_name.id_for_label }}" >{{ form.first_name.label }}</label>
{{ form.first_name|addcss:"form-control"}}
</div>
Problem is, I render the input field with the Django template engine and don't specifiy it myself. My idea was to chain template filters:
<div >
<label for="{{ form.username.id_for_label }}" >{{ form.username.label }}</label>
{{ form.username|addcss:"form-control"|addplaceholder:user.username}}
</div>
But that didn't work because the first filter converts it to a widget:
@register.filter(name="addcss")
def addcss(field, css):
return field.as_widget(attrs={"class": css})
Maybe you can recommend me a way on how to modify that filter or tell me a complety different approach.
CodePudding user response:
When you create the form within the view you can specify an instance:
form = UserUpdateForm(instance=user_instance)
Rendering this form in the template will show values from user_instance
in the form.
You can also specify an initial
dictionary for the form but the is usually only for empty forms useful.
CodePudding user response:
form = UserUpdateForm(instance=request.user)
you have to set init data.