[Django]-Django – Admin custom field display & behavior

5πŸ‘

βœ…

To insert a <script> in an admin page the simplest thing to do is:

class ScribPartAdmin(model.ModelAdmin):
    ...
    your normal stuff...
    ...

    class Media:
        js = ('/path/to/your/file.js',)

ModelAdmin media definitions documentation

Now to add the class attribute to the textarea I think the simplest way to do it is like this:

from django import forms

class ScribPartAdmin(model.ModelAdmin):
    ...
    your normal stuff...
    ...

    class Meta:
        widgets = {'text': forms.Textarea(attrs={'class': 'mymarkup'})}

Overriding the default widgets documentation

I should add that this approach is good for a one shot use. If you want to reuse your field or JS many times, there’s better ways to do it (custom widget for the field, with JS file specified if the JS is exclusively related to the field, extending template to include a JS file at many places).

2πŸ‘

You have to create a template, put it in templates/admin/change_form_scribpart.html with this content:

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

{% block content %}
    <script type="text/javascript" src="/static/js/mymarkup.js"></script>
    {{ block.super }}
{% endblock %}

Also, don’t forget to activate this new admin template in your ScribPart ModelAdmin:

class ScribPartAdmin(admin.ModelAdmin):   
    ordering = ...
    fieldsets = ...
    change_form_template = "admin/change_form_scribpart.html"

0πŸ‘

You can send your form with json pack and get(check) with this code

results = ScribPart.all()
    for r in results :

        if r.test == id_text:
            self.response.out.write("<script type='text/javascript' src='/static/js/"+r.name+"mymarkup.js'></script>")

Leave a comment