Search code examples
pythonhtmldjangodjango-admindjango-widget

Django - Admin custom field display & behavior


Let's imagine this model:

class ScribPart(models.Model):
  name = models.CharField(max_length=50, unique=True)
  text = models.TextField()

I'd like to attach a specific class to the field text and call a specific js file. So that the admin page would be like:

...
<script type="text/javascript" src="/static/js/mymarkup.js"></script>
...
<textarea id="id_text" name="text" class="mymarkup"></textarea>
...

How can I do that with a widget and/or custom admin form ?


Solution

  • 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).