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

耗尽温柔 提交于 2019-12-01 06:27:40
frnhr

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()

If you do not really care if the field is read only but you only need to prevent users from changing it, I have found a workaround:

In the clean method of the inline modelform raise a vailidation error:

class Essai_TemperatureForm(forms.ModelForm):
    def clean(self):
        if self.has_changed() and self.initial:
            raise ValidationError(
                'You cannot change this inline',
                code='Forbidden'
            )
        return super().clean()

    class Meta(object):
    model = Essai_Temperature
    fields='__all__'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!