Django:如何在使用非模型数据时预填充表单?

编程入门 行业动态 更新时间:2024-10-24 10:18:51
本文介绍了Django:如何在使用非模型数据时预填充表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 在我的情况下,Django应用程序正在通过API保存和从外部服务获取用户数据。我得到一个具有许多用户属性的对象,例如名称,地址等

为了更新这样的信息,我使用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:如何在使用非模型数据时预填充表单?

本文发布于:2023-08-05 20:53:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1307993.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   模型   数据   如何在   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!