How to get a single widget to set 2 fields in Djan

2019-04-01 15:01发布

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?

3条回答
再贱就再见
2楼-- · 2019-04-01 15:26

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.

查看更多
贼婆χ
3楼-- · 2019-04-01 15:31

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

查看更多
成全新的幸福
4楼-- · 2019-04-01 15:38

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

查看更多
登录 后发表回答