39

I'm gonna slightly simplify the situation. Let's say I've got a model called Lab.

from django.db import models

class Lab(models.Model):
    acronym = models.CharField(max_length=20)
    query = models.TextField()

The field query is nearly always the same as the field acronym. Thus, I'd like the query field to be automatically filled in after entering text in the acronym field in the Django admin interface. This task must be performed by a jQuery script.

So if I take an example: you want to add a new lab to the database through the Django admin interface. You click the add button and you land on the empty form with the two fields. You manually fill in the acronym field with a value such as ABCD and then the query field should antomatically be completed with the same value, that means ABCD.

How should I proceed?

Serjik
  • 10,543
  • 8
  • 61
  • 70
user2282405
  • 873
  • 2
  • 9
  • 10

1 Answers1

82

To add media to the admin you can simply add it to the meta class Media of your admin class, e.g.:

admin.py

class FooAdmin(admin.ModelAdmin):
    # regular stuff
    class Media:
        js = (
            '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js', # jquery
            'js/myscript.js',       # project static folder
            'app/js/myscript.js',   # app static folder
        )

admin.site.register(Foo, FooAdmin)

Mind the trailing comma if you only have one file included, as it has to be a tuple. You can also opt in css this way.

The admin already has (an older version) of jquery included. To shortcut it for usage add this to the top of the 'myscript' file:

if (!$) {
    $ = django.jQuery;
}

To solve your problem, I would extend the admin. You can add a js event to any DOM node to trigger an ajax call in your myscript file to the correct admin view for handling.

Juuso Ohtonen
  • 8,826
  • 9
  • 65
  • 98
Hedde van der Heide
  • 21,841
  • 13
  • 71
  • 100
  • 2
    This may have changed since it's an old question, but as of Django 1.8.1, the css is specified as a dictionary with the key being the target media and the value being the tuple of paths as above. Use comma separation to target multiple medias or 'all' if it's non-specific. – squarelogic.hayden Jul 07 '15 at 13:54
  • 2
    ```(function($){ // your code })(django.jQuery); ``` – rabbit.aaron Dec 13 '18 at 03:58
  • Better and shorter `django.jQuery(function($) { // stuff })` – Felipe Buccioni May 09 '21 at 02:58