Django: How to pre-populate a form when using non-model data?

假如想象 提交于 2019-12-11 05:39:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!