1

I added a custom page containing a form in my Django admin site. To do this, I wrote this code:

class MyForm(forms.Form):

    class Media:
        js = ('js/foo.js',)

    my_number = forms.IntegerField(
        required=True,
        min_value=1,
        max_value=10,
        label='Magic number'
    )

And this code:

form = MyForm()
context = self.each_context(request)
context.update({'form': form})
return render(request, 'admin/players/foo.html', context)

My problem is the JS does not execute/load because if I put the following single line in it, nothing happens:

alert('foo');

What's strange is I have a very similar thing somewhere else and it works like a charm:

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('bar1', 'bar2',)
    search_fields = ('bar1',)

    class Media:
        js = ('js/bar.js',)

I checked the media property in both cases and I got this:

<script type="text/javascript" src="/static/js/foo.js"></script>
<script type="text/javascript" src="/static/js/bar.js"></script>

So at least, the path to the file is OK.

What did I miss?

UPDATE: Following the accepted answer, I added the following lines in my template:

{% block extrahead %}
    {{ form.media }}
{% endblock %}
Rodolphe
  • 1,689
  • 1
  • 15
  • 32
  • Both files appear under `utils` folder. But you are trying to import it as `js/foo.js`. Did you try to change it like `js/utils/foo.js` ? – alioguzhan Dec 16 '16 at 09:28

1 Answers1

1

You need to add {{form.media}} into foo.html template.

neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
  • You saved my day. Thank you so much! – Rodolphe Dec 16 '16 at 09:46
  • Oops... My JS loads but now I get the "django is not defined" error... Do you happen to know the solution to this problem as well? – Rodolphe Dec 16 '16 at 09:54
  • 1
    @Rodolphe check this http://stackoverflow.com/questions/10583652/uncaught-referenceerror-django-is-not-defined – neverwalkaloner Dec 16 '16 at 09:59
  • Thanks. It indeed does the trick. But I'm surprised I didn't need to manually include jquery when I customized my other page. It was automatically included... Thanks anyway! – Rodolphe Dec 16 '16 at 10:39