django modeladmin, readonly_fields and boolean fields

a 夏天 提交于 2020-01-06 01:52:06

问题


I've a simple model with a boolean field in it, and the related admin view:

# in models.py
class MyModel(models.Model):
    ...
    my_field = models.BooleanField(...)

# in admin.py
class MyModelAdmin(admin.ModelAdmin):

    readonly_fields ("my_field", ...)

My problem is that now my boolean field appears always empty, independently from the actual value of the field itself.

I didn't find any solution to this problem, does it happen only to me?

I don't know if it may be relevant, but I'm using grappelli == 2.4.5

Thanks


回答1:


Ok,

after some searching I've found a solution (perfectible, but a good starting point). I've simply overridden the get_form(...) model in my concretization of ModelAdmin:

def get_form(self, *args, **kwargs):

    form = super(SupplierAdmin, self).get_form(*args, **kwargs)

    for field_name in self.fake_readonly_fields:
        form.base_fields[field_name].widget.attrs["disabled"] = "disabled"


    return form

I renamed the list of my readonly fields to fake_readonly_fields, in order not to mess with Django readonly_fields. This works for textboxes, checkboxes and selects (I guess also for radio buttons, but I didn't verify it...). Now I'm looking for a solution for upload file inputs ...

Btw I don't know if this solution can cause "security" problems (e.g. some crafted message to the server can overcome my html-disabled fields, and pass new data to overwrite old values ...) but that's a different (still relevant) topic



来源:https://stackoverflow.com/questions/22701035/django-modeladmin-readonly-fields-and-boolean-fields

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