How to set initial value for read only field

跟風遠走 提交于 2019-12-11 21:22:51

问题


I have a django application which is using django.contrib.admin for administrative tasks.

For one model I now need to add a field which indicates which part of the code each row was created from. I am using readonly_fields to prevent this value from being changed through the administration interface.

A default value in this field will tell me that the row was either

  • created before the field was introduced
  • created by code which has not been updated to set the field
  • created through the administration interface

But I need better granularity than that. In particular I want to be able to distinguish between a row created by code which doesn't know about the field, and a row created through the administration interface.

Is there some way my ModelAdmin class can specify an initial value for a field mentioned in readonly_fields?


回答1:


One way to do this is,

def get_form(self, request, caja=None, **kwargs):
    self.form = YourModelForm

    form = super(YourModelAdmin, self).get_form(request, caja, **kwargs)
    form.base_fields['field'].initial = your_initial_data
    return form



回答2:


I found this solution, which appears to work:

class Admin(ModelAdmin):
    readonly_fields = ('created_by',)
    def save_form(self, request, form, change):
        r = super(Admin, self).save_form(request, form, change)
        if not change:
            assert r.created_by == CREATED_BY_UNKNOWN
            r.created_by = CREATED_BY_ADMIN
        return r

CREATED_BY_UNKNOWN and CREATED_BY_ADMIN are values defined elsewhere in my code.



来源:https://stackoverflow.com/questions/32796938/how-to-set-initial-value-for-read-only-field

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