如何让单个小部件在 Django 中设置 2 个字段?
我得到了一个包含 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在表单上定义纬度和经度字段;将它们设置为使用 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
我使用了重写
full_clean
方法来进行数据分割。使用clean_FIELD
方法已经太晚了。I've used overriden
full_clean
method for data splitting. Usingclean_FIELD
method is too late.我最终在我的管理员上设置了一个自定义表单,其中包含一个额外的非必填字段,该字段有一个控制地图的小部件,并设置了一个像 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.