tags:

views:

123

answers:

1

I want to create a model, that will set editable=False on creation, and editable=True on editing item. I thought it should be something like this:

 home = models.ForeignKey(Team, editable=lambda self: True if self.id else False)

But it doesn't work. Maybe something with overriding the init can help me, but i don't sure what can do the trick. I know i can check for self.id in save() method, but is too late, i want this kind of logic in admin app when im filling the fields.

+4  A: 

Add the following (a small extension of this code) to your admin.py:

from django import forms

class ReadOnlyWidget(forms.Widget):
    def __init__(self, original_value, display_value):
        self.original_value = original_value
        self.display_value = display_value

        super(ReadOnlyWidget, self).__init__()

    def render(self, name, value, attrs=None):
        if self.display_value is not None:
            return unicode(self.display_value)
        return unicode(self.original_value)

    def value_from_datadict(self, data, files, name):
        return self.original_value

class ReadOnlyAdminFields(object):
    def get_form(self, request, obj=None):
        form = super(ReadOnlyAdminFields, self).get_form(request, obj)
        fields = getattr(self, 'readonly', [])
        if obj is not None:
            fields += getattr(self, 'readonly_on_edit', [])

        for field_name in fields:
            if field_name in form.base_fields:
                if hasattr(obj, 'get_%s_display' % field_name):
                    display_value = getattr(obj, 'get_%s_display' % field_name)()
                else:
                    display_value = None

                form.base_fields[field_name].widget = ReadOnlyWidget(getattr(obj, field_name, ''), display_value)
                form.base_fields[field_name].required = False

        return form

You can then specify that certain fields should by readonly when the object is edited:

class PersonAdmin(ReadOnlyAdminFields, admin.ModelAdmin):
    readonly_on_edit = ('home',)

admin.site.register(Person, PersonAdmin)
Vebjorn Ljosa