5

How does django display the default value in a textfield to form.

<input type="text" name="{{ form.username}}" value="{{ costumer.username}}"><p>

it shows a textfield follow by costumer.username in browser, I want to have the username as default value in the textfield, How can i do that?

2
  • what is customer ? is it another object Commented Apr 19, 2013 at 14:47
  • yeah , they both are objects and have been passed in a dictionary to a template. Commented Apr 19, 2013 at 14:50

2 Answers 2

7

Use initial parameter to a form:

form = Form(initial={'username': costumer.username})

and to display input in template you need just this:

{{ form.username }}<br/>

https://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values

Sign up to request clarification or add additional context in comments.

2 Comments

I need to add a custom class to the field. Any way to write custom HTML and put the default there? <input value='{{ form.username.initial }}> doesn't work and form.username.value neither.
@CGFoX i think you talk about customizing field widget (class is passed to widget attrs dict) - docs.djangoproject.com/en/3.1/ref/forms/widgets/…
2

In your view:

myForm = MyForm(initial={'username': costumer.username })

and in the template:

{{myForm.username|safe}}

Should do the trick.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.