Django:如何在使用非模型数据时预填充表单? [英] Django: How to pre-populate a form when using non-model data?

查看:154
本文介绍了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:如何在使用非模型数据时预填充表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆