简体   繁体   中英

Django - adding extra html in admin

I have a model class like this

models.py

class Places(models.Model):
    name = models.CharField(max_length=50)   
    address = models.CharField(max_length=50)  
    tel = models.CharField(max_length=50)

I want to put a google map under the address field and have a custom button next to the address field. The button is used to pin point the location when user click on it, based on the address input.

So, my question is how do I insert the button next to the address fields and html tags under it for map rendering?

Thanks.

You'll have to write a custom widget. Take a look at this , this and django documentation . You'll probably need to write south introspection rules

There is a django-easy-maps module that can do exactly what you need (besides other features):

django-easy-maps provides basic widget that displays a map under the address field. It can be used in admin for map previews.

Note that you would not need to change your model and write any specific migrations. It works with either CharField , or TextField out of the box.

Follow the installation instructions and add the following to the admin.py of your app:

from django import forms
from django.contrib import admin
from easy_maps.widgets import AddressWithMapWidget
from my_app.models import Places

class PlacesAdmin(admin.ModelAdmin):
    class form(forms.ModelForm):
        class Meta:
            widgets = {
                'address': AddressWithMapWidget({'class': 'vTextField'})
            }

admin.site.register(Places, PlacesAdmin)

I end up refer to this tutorial to create a custom widget.

For anyone who are interested, here are my codes

widgets.py

class AddressFieldWidget(forms.TextInput):
     def render(self, name, value, attrs=None):
        html = super(AddressFieldWidget, self).render(name, value,
                                            attrs)
        html =  html + """  <input type="button" value="GeoCode" class="getgeo btn"><br><br><label>Map</label><div id="gmap">This is for map rendering</div>""" 
        return mark_safe(html)  

admin.py

def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'address':
             kwargs['widget'] = AddressFieldWidget

        return super(AdminListing,self).formfield_for_dbfield(db_field,**kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM