Задать вопрос

Тел: +7 965 3737 888





Dynamically add inlines

<p>These functions use JQuery to dynamically add new entries for stacked or tabular inlines on a change form. To enable it, change the parent model to include this Javascript as well as JQuery. Here's an example:</p>
class MeetingAdmin(admin.ModelAdmin):
    inlines = [MeetingDonationInline, MeetingExtraInline]

    class Media:
        js = ["/media/jquery-1.3.2.min.js",

Вопрос полезен? Да0/Нет0

Ответы (6):

Ответ полезен? Да0/Нет0

i noticed that js for prepopulated fields (like slugs) doesn't work with the newly created inlines, since the necessary script (from django/contrib/admin/templates/admin/prepopulated_fields_js.html) isn't also created. i don't know what the solution to this is, since in some cases (extra=0 for inlines with slugfields) there wouldn't even be script to duplicate.

Ответ полезен? Да0/Нет0

Just a tip, it's best practice to always use semicolons in javascript. The fact that they aren't enforced is definitely a bug and not a feature of the language. (One example of why: if this script was minified it wouldn't work because minification removes newlines)

Regardless, very handy script. Cheers.

Ответ полезен? Да0/Нет0

If there is an inline with max_num=1, the javascript function should not be there, {% ifnotequal inline_admin_formset.formset.max_num 1 %} in your template code prevents this from happening.

Ответ полезен? Да0/Нет0

An improvement would be to add the "add a new inline" button using JavaScript

Good idea. The reason I didn't do this was because I had already extended the stacked and tabular inline templates in my project for other purposes. I doubt many others are in that situation, so I went ahead and added that feature.

Ответ полезен? Да0/Нет0

I did something similar. The bit I disagree with here is the 'copy the appropriate file ... into your project's template directory' bit. That makes upgrading Django a headache.

Instead I simply created the 'Add' link dynamically: $('.inline-group').append('[HTML_REMOVED]Add another[HTML_REMOVED]');

(Jquery used in that example)

Ответ полезен? Да0/Нет0

An improvement would be to add the "add a new inline" button using JavaScript . This would give you two advantages: first, there's no need to alter the template itself (you can just use Media.js to add the script). Secondly, it means that users without JavaScript won't see a link that doesn't do anything.