I want to display an embedded map on an admin form when data already exists in the db. I have the following code:
models.py
class Address(models.Model):
address = models.CharField()
def address_2_html(self):
if self.address:
# Return html for an embedded map using the entered address.
return embedded_map_html
else:
return ''
address_2_html.allow_tags = True
admin.py
class AddressAdmin(admin.ModelAdmin):
fieldsets = [(label, {'fields': ['address','address_2_html']}),]
This doesn't work. I get an error:
'AddressAdmin.fieldsets[1][1]['fields']' refers to field 'address_2_html' that is missing from the form.
Another thing I tried was using the 'description' option for 'fieldsets', however, 'address_2_html' is not accessible within the scope of AddressAdmin. I did succeed at embedding a static map using 'description' which was cool but not cool enough.
str function in a django model returns a string that is exactly rendered as the display name of instances for that model.
It's just a way for you to be able to group the fields on a Model Admin Page. Just implement the example in the documentation and it should become apparent for you.
To create a new instance of a model, instantiate it like any other Python class: class Model (**kwargs) The keyword arguments are the names of the fields you've defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save() .
save() method from its parent class is to be overridden so we use super keyword. slugify is a function that converts any string into a slug. so we are converting the title to form a slug basically.
Like that (from memory):
class AddressAdmin(admin.ModelAdmin):
fieldsets = [(label, {'fields': ['address','address_2_html']}),]
readonly_fields = ['address_2_html']
def address_2_html(self, obj):
return obj.address_2_html()
address_2_html.allow_tags = True
address_2_html.short_description = 'Address display'
Problem solved by overriding get_fieldsets() since the get_fieldsets() method allows access to the model object Address.
def get_fieldsets(self, request, obj=None):
fs = [
(self.label, {'fields': ['address',]}),
('Map', {'fields': [], # required by django admin
'description':obj.address_2_html(),
}),
]
return fs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With