How to get a single widget to set 2 fields in Django?

穿精又带淫゛_ 提交于 2020-01-01 06:46:46

问题


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?


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/2856790/how-to-get-a-single-widget-to-set-2-fields-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!