Django admin readonly for existing field but allowing to add new inline if you click + Add another

前端 未结 2 378
天涯浪人
天涯浪人 2021-01-14 02:33

I know, that question was asked but it is not clear to me.

I have put all fields \'readonly field\' for Essai_TemperatureInline.

I would like to

2条回答
  •  离开以前
    2021-01-14 03:16

    Unfortunately, you can't. At least not in a nice way, trough Python, as you would expect if you know how to do it with regular ModelAdmin. It's a bug in the admin, documented in Ticket #15602

    What you can do is make use of JavaScript. Use this selector:

    .inline-group tr.has_original
    

    The has_original class is applied to every inline that represents an already-saved model instance.

    So, in the Essai_TemperatureInline class, make all your fields editable (non-readonly), and then use JS (jQuery, I guess) to make some of the fields readonly:

    django.jQuery('.inline-group tr.has_original #id_somefield').attr('readonly', 'readonly');
    

    See The Documentation about how to add your own JS to admin pages. Basically:

    class ArticleAdmin(admin.ModelAdmin):
        class Media:
            css = {
                "all": ("my_styles.css",)
            }
            js = ("my_code.js",)
    

    security note:

    This can obviously easily be tricked over, with Firebug or similar browser tool. So make sure to take that into account if necessary, and do some checks, probably somewhere on formset.clean()

提交回复
热议问题