Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django admin: How to customize one field in fieldsets?

I try to make one field in django admin's fieldsets to show only certain data, but according to django document, only an example of list_display is shown to be able to customize. I tried the similar approach on fieldsets like the following:

In models.py:

def ports_with_same_scanner(self):
    return PortList.objects.filter(scanner=self.scanner)
ports_with_same_scanner.short_description = 'port_lists'

In admin.py, this won't work:

fieldsets = (
            ('Scan Template', { 
            'fields': ( ('name', 'scanner', 'ports_with_same_scanner',), 'comment', ('in_use',
                'fc_growing', 'nc_growing'), 'nvt_prefs')
            }),
)

However, if I do this:

list_display = ('name', 'scanner', 'ports_with_same_scanner', 'comment', 'in_use', 'fc_growing', 'nc_growing', 'nvt_prefs')

the ports_with_same_scanner works just fine. The problem is that I don't want to change my display from fieldsets to list_display, I wonder how can I achieve the same functionality. Thanks.

like image 282
Shang Wang Avatar asked Mar 05 '13 15:03

Shang Wang


People also ask

How do I make a field editable in Django?

To use editable in a field you must specify either of following settings: null=True and blank=True, so that your field doesn't give required error during model save. default=value, this will also set the field to some value so that it doesn't give suspicious errors to admin user.

What is Fieldsets in Django admin?

fieldsets is a list of two-tuples, in which each two-tuple represents a <fieldset> on the admin form page. (A <fieldset> is a “section” of the form.)

What is Django jazzmin?

Welcome to Jazzmin, intended as a drop-in app to jazz up your django admin site, with plenty of things you can easily customise, including a built-in UI customizer.


1 Answers

I don't know if real problem at past ... I always using simple approach - to adding a name of method to the readonly_fields = ()

Example:

models.py

class My(models.Model):

    def custom_name(self):
        return 'test'
    custom_name.allow_tags = False
    custom_name.short_description = 'custom_name'

admin.py

class MyAdmin(admin.ModelAdmin):
    fieldsets = (
            (None, {
                    'fields': ('custom_name', )
            }),
    )
    readonly_fields = ('custom_name', )

It must be working Django >=1.7 It seems the approach can be apply to early version of Django^ but I don't testing

like image 54
Abbasov Alexander Avatar answered Oct 03 '22 11:10

Abbasov Alexander