为了更新这样的信息,我使用Django的本机表单,具有速记模板格式,例如: {{ edit_account_form.as_p}}
当我显示表单来编辑信息时,我想预先填写数据,用户对象。我知道我可以将对象传递到模板中,并将这些值传递到每个输入字段的val和占位符中,但这将使我完全重新创建输入的表单,我不希望这样输入。
可能?
解决方案使用 initial 在运行时声明表单域的初始值。例如,您可能需要使用当前会话的用户名填写用户名字段。
f = ContactForm(initial = {'subject':'Hi there!'})
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?
解决方案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!'})
更多推荐
Django:如何在使用非模型数据时预填充表单?
发布评论