如何以 django 形式将初始值传递给图像字段

发布于 2024-12-29 12:42:14 字数 458 浏览 2 评论 0原文

目前我正在使用类似的东西:

initialValues={
    'textField1':'value for text field 1',
    'textField2':'value for text field 2',
    'imageField': someModel.objects.get(id=someId).logo
    }

form = myForm(initial=initialValues)

当我如上所述调用 myForm 时,初始值按预期显示:textField1、textField2 和 imageField(带有当前选项:linkToImage、清除复选框和更改:)

但是当我保存表单时, imageField 字段中没有保存任何内容(检查数据库,我看到 imageField 字段为空)。

我知道我在这里错过了一些东西,但我不知道是什么。有什么建议吗?

Currently I am using something like:

initialValues={
    'textField1':'value for text field 1',
    'textField2':'value for text field 2',
    'imageField': someModel.objects.get(id=someId).logo
    }

form = myForm(initial=initialValues)

When I call myForm as above, the initial values are displayed as expected: the textField1, textField2 and imageField (with the options Currently: linkToImage, Clear check box and Change: )

But when I save the form, there is nothing saved in the imageField field (checking the database and I see the imageField field blank).

I know that I miss something here, but I cannot figure out what. Any tips?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

乄_柒ぐ汐 2025-01-05 12:42:14

我通过

request.FILES['imageField']=someModel.objects.get(id=someId).logo

在保存表单之前进行分配解决了我的问题。耶伊

I solved my issue by assigning

request.FILES['imageField']=someModel.objects.get(id=someId).logo

just before I save the form. Yeey

回忆那么伤 2025-01-05 12:42:14

创建表单时需要将数据传入表单。

initialValues={
    'textField1':'value for text field 1',
    'textField2':'value for text field 2',
    'imageField': someModel.objects.get(id=someId).logo
    }
form = myForm(data=request.POST, initial=initialValues)

如果您还没有这样做,我建议使用 基于类视图。使用 FormView 您可以轻松覆盖 get_initial_data( ) 函数,指定您的值,然后让视图负责传递给表单以保存它的其他内容。如果您想保存模型(我想您就是这样),请查看 CreateView 和 UpdateView。

如果我确切地知道您如何/何时初始化该表单,我可以更加确定这个答案。

You need to pass in the data to the form when creating it.

initialValues={
    'textField1':'value for text field 1',
    'textField2':'value for text field 2',
    'imageField': someModel.objects.get(id=someId).logo
    }
form = myForm(data=request.POST, initial=initialValues)

If you're not doing so already, I would suggest using class-based views. With a FormView you can easily override the get_initial_data() function, specify your values, and then let the view take care of what other things to pass on to the form to save it. If you're trying to save a model (which I think you are), check out the CreateView and UpdateView.

I could be more sure about this answer if I knew exactly how/when you were initializing that form.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文