Django admin: hide read-only fields in new posts?

I am using a Django admin site with some readonly fields in the entries:

class BookAdmin(admin.ModelAdmin):
    fieldsets = [
    (None, {'fields': ['title', 'library_id', 'is_missing', \
                       'transactions_all_time']}),
    ]
    readonly_fields = ['transactions_all_time',]
    list_display = ('library_id', 'author', 'title')

This works great when editing posts - the field transactions_all_timeis read-only as I want.

However, when adding new entries, this behaves a bit strange. I get a read-only section at the bottom of the page that I cannot edit, and at the moment it does not matter.

It would be much better if this field was completely absent when adding new entries.

Is there a Django option to display read-only fields when adding a new record? I know that I can hack CSS on add_form.htmlto hide it, but is there a better way?

Thank.

+5
4

. :

class MyModelAdmin(admin.ModelAdmin):
    readonly_fields = ('field_one',)
    def get_readonly_fields(self, request, obj=None):
        if obj: # Editing
            return self.readonly_fields
        return ()
+13

:

def get_fieldsets(self, request, obj=None):
    def if_editing(*args):
        return args if obj else ()
    return (
        (None, {
            'classes': ('wide',),
            'fields': if_editing('admin_thumb', 'admin_image',) +
                      ('original_image', 'user', 'supplier', 'customer', 'priority',)}
        ),
    )  

, - , obj.

+3

. ( ) "" ( "" ), :

class PhotoAdmin(admin.ModelAdmin):
readonly_fields = ('admin_image', 'admin_thumb', )
search_fields = ('filename', 'user', 'supplier', 'customer')
list_display= ('admin_thumb','filename', 'user', 'supplier', 'customer')
#fields = ('admin_thumb', 'admin_image', 'original_image', 'user', 'supplier', 'customer')


def get_fieldsets(self, request, obj=None):
    fieldset_existing = (
        (None, {
            'classes': ('wide',),
            'fields': ('admin_thumb', 'admin_image',
                'original_image', 'user', 'supplier', 'customer', 'priority',)}
        ),
    )
    fieldset_new = (
        (None, {
            'classes': ('wide',),
            'fields': ('original_image', 'user', 'supplier', 'customer', 'priority',)}
        ),
    )
    if obj: # Editing
        return fieldset_existing
    return fieldset_new

#fields . , "", .

+1

, arg editable .

class Book(models.Model):
    transactions_all_time = models.BooleanField(editable=False)

ModelAdmin , .

0
source

All Articles