SVG widget for the Admin

178 views
Skip to first unread message

Mike Dewhirst

unread,
May 31, 2021, 9:28:59 PM5/31/21
to Django users
I collect the svg source for an image from a public API and store it in
a models.TextField. I have no difficulty displaying it in a normal view
and my own template. Nothing special, it just emerges. I don't even need
a 'safe' filter.

However, I really want to display such images in the Admin. At this
stage all it displays is the svg source.

What is the correct way to make the image appear in the Admin?

Do I need a special field inheriting from TextField? Do I need a special
widget? Is there a way to mark admin field values as safe?

Thanks for any hints

Mike

--
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Just
ask and I'll send it to you. Your email software can handle signing.


OpenPGP_signature

Derek

unread,
Jun 1, 2021, 9:44:55 AM6/1/21
to Django users
You haven't defined where in the admin interface you want this image to be displayed?  A table?

I have not tried this, but could you not create an additional field on your model that returns the HTML-encoding needed to display the SVG?

E.g. 

class MyModel():
    svg_text = CharField()

    def _the_svg(self):
        return """<svg width="100" height="100">%s</svg>""" % self.svg_text
        _the_svg.allow_tags = True
        
I am not sure about editing visually, however - I would expect that would require a specialised widget.

HTH
Derek


Mike Dewhirst

unread,
Jun 2, 2021, 4:05:11 AM6/2/21
to django...@googlegroups.com
On 1/06/2021 11:44 pm, Derek wrote:
> You haven't defined where in the admin interface you want this image
> to be displayed?  A table?
>
> I have not tried this, but could you not create an additional field on
> your model that returns the HTML-encoding needed to display the SVG?

Derek, thanks for responding. I tried your suggestion and had no success.

Where in the admin? Just among a normal roster of fields. The svg is a
molecular structure and the image needs to appear for example just after
the molecular formula. I collect the actual svg code via a public API on
saving the record.

>
> E.g.
>
> class MyModel():
>     svg_text = CharField()

in my case it is ...

class chemical(models.Model):
    ...
    ddstructure = models.TextField(
        null=True,
        blank=True,
        verbose_name="2D structure",
    )

>
>     def _the_svg(self):
>         return """<svg width="100" height="100">%s</svg>""" %
> self.svg_text
>         _the_svg.allow_tags = True

Not sure where this should live for the Admin to call it and display the
image.


> I am not sure about editing visually, however - I would expect that
> would require a specialised widget.

It is read-only in all cases.

I was thinking a widget might be needed just for display. The svg code
arrives complete with tags so really all it needs is a mechanism to
persuade the admin it is safe to render as is.

I haven't seen such a (probably insecure) "feature" previously. I've
looked through the docs but haven't found it yet.

Thanks again

Mike


>
> HTH
> Derek
>
>
> On Tuesday, 1 June 2021 at 03:28:59 UTC+2 Mike Dewhirst wrote:
>
> I collect the svg source for an image from a public API and store
> it in
> a models.TextField. I have no difficulty displaying it in a normal
> view
> and my own template. Nothing special, it just emerges. I don't
> even need
> a 'safe' filter.
>
> However, I really want to display such images in the Admin. At this
> stage all it displays is the svg source.
>
> What is the correct way to make the image appear in the Admin?
>
> Do I need a special field inheriting from TextField? Do I need a
> special
> widget? Is there a way to mark admin field values as safe?
>
> Thanks for any hints
>
> Mike
>
> --
> Signed email is an absolute defence against phishing. This email has
> been signed with my private key. If you import my public key you can
> automatically decrypt my signature and be sure it came from me. Just
> ask and I'll send it to you. Your email software can handle signing.
>
>
> --
> You received this message because you are subscribed to the Google
> Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to django-users...@googlegroups.com
> <mailto:django-users...@googlegroups.com>.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/520bf296-ec68-48ad-8fe2-f106823efac2n%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/520bf296-ec68-48ad-8fe2-f106823efac2n%40googlegroups.com?utm_medium=email&utm_source=footer>.
OpenPGP_signature

Derek

unread,
Jun 2, 2021, 9:39:08 AM6/2/21
to Django users
When you say "I tried your suggestion and had no success." what exactly did you try  - i.e. what code did you use and what errors did you get?

WRT "Not sure where this should live for the Admin to call it and display the image." - it lives exactly as I showed it in my example; its a user-defined property for the model in which the SVG text is stored.  You can use it in the admin as you would the normal model fields. 

There is a good example of defining and using your own derived 'field'  here:
https://realpython.com/customize-django-admin-python/#modifying-a-change-list-using-list_display

(Please note that to show HTML strings, you need to use the format_html() method. Ignore mt previous reference to "allow_tags" as this is deprecated.)

Derek

Mike Dewhirst

unread,
Jun 2, 2021, 7:10:07 PM6/2/21
to django...@googlegroups.com
Derek

I pretty much tried what you suggested. I dont have access to my machine atm so that's all I can really say. 

I looked at the link and understand the list customisation because I already use it elsewhere. 

It does look like I'll have to switch in my own template so I can include a safe filter.

Thanks again

Mike



--
(Unsigned mail from my phone)

To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/518a9b56-de5a-46b8-8578-89bd99f20f4fn%40googlegroups.com.

Derek

unread,
Jun 3, 2021, 2:00:03 AM6/3/21
to Django users
Hi Mike

OK, if you have more specific feedback I will try to respond.

I doubt you need a specific template as the SVG should be displayable by a modern browser using Django's built-in options.

Mike Dewhirst

unread,
Jun 3, 2021, 2:22:57 AM6/3/21
to django...@googlegroups.com
On 3/06/2021 4:00 pm, Derek wrote:
> >
> > E.g.
> >
> > class MyModel():
> >     svg_text = CharField()
>
> in my case it is ...
>
> class Chemical(models.Model):
>     ...
>     ddstructure = models.TextField(
>         null=True,
>         blank=True,
>         verbose_name="2D structure",
>     )
>

The above is unchanged.

# admin
class ChemicalAdmin(admin.ModelAdmin):

    def _ddstructure(self, obj):
        return mark_safe(obj.ddstructure)
    ...
    fieldsets = (
        (
            None,
            {
                "fields": (
                    "ddstructure",        # displays svg code
                    "_ddstructure",
                    ...
            }
    ),

FYI it works perfectly as a column in the list display - but I don't
need it there, rather in the page for the chemical.

This is what happens if it is included in the fieldsets "fields" roster.


FieldError at /admin/chemical/chemical/17/change/

Unknown field(s) (_ddstructure) specified for Chemical. Check fields/fieldsets/exclude attributes of class ChemicalAdmin.

Request Method: GET
Request URL: http://localhost:8088/admin/chemical/chemical/17/change/
Django Version: 3.2.3
Exception Type: FieldError
Exception Value:

Unknown field(s) (_ddstructure) specified for Chemical. Check fields/fieldsets/exclude attributes of class ChemicalAdmin.

Exception Location:
D:\Users\mike\envs\xxai\lib\site-packages\django\contrib\admin\options.py,
line 712, in get_form
Python Executable: D:\Users\mike\envs\xxai\Scripts\python.exe
Python Version: 3.8.3


Cheers

Mike


> >
> >     def _the_svg(self):
> >         return """<svg width="100" height="100">%s</svg>""" %
> > self.svg_text
> >         _the_svg.allow_tags = True
>


OpenPGP_signature

Derek

unread,
Jun 4, 2021, 3:15:45 AM6/4/21
to Django users
Hi Mike

The SVG is not going to display as SVG in a *form* - for that you'd need a widget, or perhaps just let users edit the text.

Did you try displaying in the normal admin lists? This was my understanding of where you wanted to see it and the code snippets I posted were for that purpose.

If you want to see it as "read only" in the form, but shown as SVG, perhaps you need a custom model template (https://docs.djangoproject.com/en/dev/ref/contrib/admin/#templates-which-may-be-overridden-per-app-or-model)

Derek

Mike Dewhirst

unread,
Jun 4, 2021, 3:52:17 AM6/4/21
to django...@googlegroups.com
On 4/06/2021 5:15 pm, Derek wrote:
> Hi Mike
>
> The SVG is not going to display as SVG in a *form* - for that you'd
> need a widget, or perhaps just let users edit the text.

It will always be readonly.  Forever.

>
> Did you try displaying in the normal admin lists? This was my
> understanding of where you wanted to see it and the code snippets I
> posted were for that purpose.

I did try that and it did show the svg image - but that isn't where I
want it. It needs to be in the Admin displayed form.

>
> If you want to see it as "read only" in the form, but shown as SVG,

but shown as an image
I think that's where I need to go. Might be easier than a widget -
unless someone has built one already?

It would be quite handy to use mark_safe() somewhere ...

Thanks

Mike
> --
> You received this message because you are subscribed to the Google
> Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to django-users...@googlegroups.com
> <mailto:django-users...@googlegroups.com>.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/4862b67b-e5e9-40a3-b3aa-1666f4739703n%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/4862b67b-e5e9-40a3-b3aa-1666f4739703n%40googlegroups.com?utm_medium=email&utm_source=footer>.
OpenPGP_signature

Mike Dewhirst

unread,
Jun 6, 2021, 7:33:25 PM6/6/21
to Django users
On 4/06/2021 5:15 pm, Derek wrote:
> Hi Mike
>
> The SVG is not going to display as SVG in a *form* - for that you'd
> need a widget, or perhaps just let users edit the text.

OK - I'm outta my depth here. I've looked at the AdminTextareaWidget
which is probably based on the TextInput built-in widget but see no way
to influence what it does. In theory I'd create a new widget inheriting
from that and use mark_safe() somehow.

Then I would need to tell the admin form to use it for my ddstructure field.

BUT see my template effort below

>
> Did you try displaying in the normal admin lists? This was my
> understanding of where you wanted to see it and the code snippets I
> posted were for that purpose.
>
> If you want to see it as "read only" in the form, but shown as SVG,
> perhaps you need a custom model template
> (https://docs.djangoproject.com/en/dev/ref/contrib/admin/#templates-which-may-be-overridden-per-app-or-model)

Again, my feet don't touch bottom. I tried adding some code to
change_form.html like this ...

{% extends "admin/change_form.html" %}

{% block content %}{{ block.super }}
{% if original.ddstructure %}
    {{ original.ddstructure | safe }}
{% else %}
    <p>No 2D structure image </p>
{% endif %}

{% endblock %}

This kinda worked. It comes after block.super so it displays the svg
image correctly but at the bottom of the page. AND the raw (or safe)
code also displays in the location where I really want the image.

So close but ...

How do I get it to display inline in the proper place?

Many thanks for hanging in there

Cheers

Mike
> --
> You received this message because you are subscribed to the Google
> Groups "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to django-users...@googlegroups.com
> <mailto:django-users...@googlegroups.com>.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/4862b67b-e5e9-40a3-b3aa-1666f4739703n%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/4862b67b-e5e9-40a3-b3aa-1666f4739703n%40googlegroups.com?utm_medium=email&utm_source=footer>.
OpenPGP_signature

Mike Dewhirst

unread,
Jun 6, 2021, 9:51:00 PM6/6/21
to Derek, Django users
On 6/06/2021 6:14 pm, Derek wrote:
RE - "I've looked at the AdminTextareaWidget which is probably based on the TextInput built-in widget but see no way to influence what it does. " and "How do I get it to display inline in the proper place?"

There seems to be similar question on SO:


The answer with AdminFooWidget() and FooAdminForm() seems closest to your use case.

Thanks for that. Unfortunately the answer at that link is ten years old and I think Django Admin must have moved on since then. I'm still trying to debug an inexplicable KeyError but I think I understand the approach.

I'll keep trying

Cheers

mike



On Sun, 6 Jun 2021 at 09:56, Mike Dewhirst <mi...@dewhirst.com.au> wrote:
On 4/06/2021 5:15 pm, Derek wrote:
Hi Mike

The SVG is not going to display as SVG in a *form* - for that you'd need a widget, or perhaps just let users edit the text.

OK - I'm outta my depth here. I've looked at the AdminTextareaWidget which is probably based on the TextInput built-in widget but see no way to influence what it does. In theory I'd create a new widget inheriting from that and use mark_safe() somehow.

Then I would need to tell the admin form to use it for my ddstructure field.

BUT see my template effort below

Did you try displaying in the normal admin lists? This was my understanding of where you wanted to see it and the code snippets I posted were for that purpose.

If you want to see it as "read only" in the form, but shown as SVG, perhaps you need a custom model template (https://docs.djangoproject.com/en/dev/ref/contrib/admin/#templates-which-may-be-overridden-per-app-or-model)
Again, my feet don't touch bottom. I tried adding some code to change_form.html like this ...

{% extends "admin/change_form.html" %}

{% block content %}{{ block.super }}
{% if original.ddstructure %}
    {{ original.ddstructure | safe }}
{% else %}
    <p>No 2D structure image </p>
{% endif %}

{% endblock %}

This kinda worked. It comes after block.super so it displays the svg image correctly but at the bottom of the page. AND the raw (or safe) code also displays in the location where I really want the image.

So close but ...

How do I get it to display inline in the proper place?

Many thanks for hanging in there

Cheers

Mike


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.


-- 
Signed email is an absolute defence against phishing. This email has
been signed with my private key. If you import my public key you can
automatically decrypt my signature and be sure it came from me. Just
ask and I'll send it to you. Your email software can handle signing.
OpenPGP_signature

Mike Dewhirst

unread,
Jun 7, 2021, 4:03:19 AM6/7/21
to Derek, Django users
Thanks Derek - it is now working as follows ...


 class Chemical(models.Model):
    ...
    ddstructure = models.TextField(null=True, blank=True, verbose_name="2D structure")
    ...


class Svg_AdminTextareaWidget(AdminTextareaWidget):
    def render(self, name, value, attrs=None, renderer=None):
        if value:
            return force_text(self.format_value(value))


class ChemicalAdmin(admin.ModelAdmin):
    ...
    def formfield_for_dbfield(self, db_field, request, **kwargs):
        if db_field.name == 'ddstructure':
            kwargs['widget'] = Svg_AdminTextareaWidget
        return super().formfield_for_dbfield(db_field, request, **kwargs)
    ...

Cheers

Mike
OpenPGP_signature

Derek

unread,
Jun 7, 2021, 5:12:38 AM6/7/21
to Mike Dewhirst, Django users
Good to hear!  Django once again proving capable, once you figure it out. 

Am reminded of the Zen:

"There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch."

Mike Dewhirst

unread,
Jun 8, 2021, 10:45:59 PM6/8/21
to Derek, Django users
Do not use this solution.

The Svg_AdminTextareaWidget code below deletes data on saving.

I think the reason might be that on saving it tries to save the image instead of the image source code.

I'm now digging deeper and will report back.

Mike
OpenPGP_signature

Mike Dewhirst

unread,
Jul 25, 2021, 11:42:40 PM7/25/21
to Derek, Django users
On 9/06/2021 12:44 pm, Mike Dewhirst wrote:
Do not use this solution.

The Svg_AdminTextareaWidget code below deletes data on saving.

I think the reason might be that on saving it tries to save the image instead of the image source code.

I'm now digging deeper and will report back.

I can't find a solution. I do have a workaround ...

Added an extra models.TextField (dstructure) and copy the ddstructure contents into it pre-save then display dstructure in the admin using the Svg_AdminTextareaWidget shown below.

So that's two fields and double the storage. I suppose disk space is cheap.

Cheers

Mike
OpenPGP_signature
Reply all
Reply to author
Forward
0 new messages