How to fill 'initial value' in Django forms with current user data?


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 class="mb-3">
   <label for="{{ form.first_name.id_for_label }}" class="form-label">{{ form.first_name.label }}</label>
   {{ form.first_name|addcss:"form-control"}}

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 class="mb-3">
   <label for="{{ form.username.id_for_label }}" class="form-label">{{ form.username.label }}</label>
   {{ form.username|addcss:"form-control"|addplaceholder:user.username}}

But that didn’t work because the first filter converts it to a widget:

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.


form = UserUpdateForm(instance=request.user)

you have to set init data.

Answered By – seokmin-kang

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published