如何让单个小部件在 Django 中设置 2 个字段?

发布于 2024-09-02 03:31:23 字数 144 浏览 5 评论 0原文

我得到了一个包含 2 个字段的模型:纬度和经度。现在它们是 2 个 CharField,但我想制作一个自定义小部件以在管理中设置它 - 正在考虑显示 Google 地图,然后获取标记的坐标。

但是我可以用 1 个小部件(单个地图)来设置 2 个不同的字段吗?

I got a model with 2 fields: latitude and longitude. Right now they're 2 CharFields, but I want to make a custom widget to set it in admin - was thinking about displaying Google Maps, then getting the coordinates of the marker.

But can I have 1 widget (a single map) to set 2 different fields?

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

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

发布评论

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

评论(3

秋日私语 2024-09-09 03:31:23

在表单上定义纬度和经度字段;将它们设置为使用 HiddenInputWidget。

在表单初始化之后,添加另一个字段,其中包含带有两个值的自定义小部件。

在该添加字段的 clean 方法中,设置 self.cleaned_data['lat'] 和 self.cleaned_data['lng'] 的值

可能有更干净的方法,但它应该有效

Define lat and long fields on your form; set them to use the HiddenInputWidget.

After the init of your form, add another field which contains your custom widget that takes two values.

In the clean method for that added field, set the values of self.cleaned_data['lat'] and self.cleaned_data['lng']

There are probably cleaner ways, but it should work

变身佩奇 2024-09-09 03:31:23

我使用了重写 full_clean 方法来进行数据分割。使用 clean_FIELD 方法已经太晚了。

I've used overriden full_clean method for data splitting. Using clean_FIELD method is too late.

转身以后 2024-09-09 03:31:23

我最终在我的管理员上设置了一个自定义表单,其中包含一个额外的非必填字段,该字段有一个控制地图的小部件,并设置了一个像 stevejalim 这样的地图小部件。不过,我没有隐藏输入字段,因为它们仍然留在视图中,而且我不介意看到它们。覆盖模板来编辑该模型并放入地图可能会更干净,但这对于应该很简单的事情来说似乎需要做很多工作。

一种解决方案是 Django 允许复杂的模型字段,其中一个模型字段对应于多个数据库列,但尚不支持(请参阅 https://code.djangoproject.com/ticket/5929

另一种情况是 Django 让我们使用对应于两个模型字段的表单字段,但似乎没有办法完成这个任务,但我找不到它的票。

I ended up setting a custom form on my admin with an extra not required field which had a widget that controls the map and setting a maps widget of that like stevejalim. However I didn't hide the input fields since they were still left in the view and I don't mind seeing them. It would probably be cleaner to override the template for editing that model instead and putting in a map, but that seemed like to much work for something that should be simple.

One solution would be if Django allowed for complex model fields where one model field corresponds to multiple db columns but that's not yet supported (see https://code.djangoproject.com/ticket/5929)

The other would be if Django would let us use a form field that corresponds to two model fields, but there doesn't seem to be a way of accomplishing that and I can't find a ticket for it.

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