问题
In my case, the Django app is saving and getting user data to/from an external service via an API. I get an object with a number of user attributes, e.g. name, address, etc.
For updating of such information I'm using Django's native forms, with the shorthand template format, say: {{ edit_account_form.as_p }}
When I display the form to edit the information, I'd like to pre-populate it with the data from the user object. I know that I can pass the object into the template and render those values into the val and placeholder of each input field, however that would requite that I completely recreate the form input by input, which I'd prefer not to.
Possible?
回答1:
Use initial to declare the initial value of form fields at runtime. For example, you might want to fill in a username field with the username of the current session.
f = ContactForm(initial={'subject': 'Hi there!'})
来源:https://stackoverflow.com/questions/21319651/django-how-to-pre-populate-a-form-when-using-non-model-data