Search code examples
pythondjangodjango-viewsdjango-formsdjango-templates

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"}}
</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 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}}
</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.


Solution

  • form = UserUpdateForm(instance=request.user)
    

    you have to set init data.