Customize Django Admin

Asked

Viewed 906 times

2

I have two classes, one is Division and the other is Group.

In the group I have FK for division.

I want to register a Storage in the Django Admin and in the Group select I want the group and division to appear in the same select, something like Group 1-Division 1 or Group 2-Division 1.

How do I customize the admin select?

class Divisao(models.Model):
    divisao = models.CharField(_('divisao'), max_length=255)


class Grupo(models.Model):
    grupo = models.CharField(_('grupo'), max_length=255)
    divisao = models.ForeignKey(Divisao, verbose_name=_('divisao'))
    responsavel = models.ForeignKey(User, verbose_name=_('tipo'))

I tried this way, but without success

py widgets.

from django.forms.widgets import Select


class DataAttributesSelect(Select):

    def __init__(self, attrs=None, choices=(), data={}):
        super(DataAttributesSelect, self).__init__(attrs, choices)
        self.data = data

    def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):  # noqa
        option = super(DataAttributesSelect, self).create_option(name, value, label, selected, index, subindex=None,
                                                                 attrs=None)  # noqa
        # adds the data-attributes to the attrs context var
        for data_attr, values in self.data.iteritems():
            option['attrs'][data_attr] = values[option['name']]

        return option

Forms.py

from django import forms
from django.contrib import admin
from .widgets import DataAttributesSelect
from .models import Storage_Volume
from sss.core.models import Grupo


class StorageVolumeAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(StorageVolumeAdminForm, self).__init__(*args, **kwargs)

        data = {'grupo': dict(Grupo.objects.values_list('grupo', 'divisao'))}
        data['grupo'][''] = ''  # empty option
        print(data)

        self.fields['grupo'].widget = DataAttributesSelect(
            choices=self.fields['grupo'].choices,
            data=data
        )

admin py.

class StorageVolumeAdmin(admin.ModelAdmin):
    list_filter = ('storages',)
    search_fields = ['storages']
    form = StorageVolumeAdminForm


admin.site.register(Storage_Volume, StorageVolumeAdmin)

1 answer

2


Bianca, if I understood what you would like to do, it would be something in this sense, correct?

Django Admin Select

If yes, what I did to get this result is much simpler than it looks, see:

Just write the method __str__ in your models. This method is calling whenever you call str(objeto). Django uses this method in several places and most notably, to display an object on the Django administration site, which is where you want to view in this case.

For more details, read.

The example below has been tested with Python 3.6 and Django 2.0

# models.py

from django.db import models
from django.contrib.auth.models import User

class Divisao(models.Model):
    divisao = models.CharField(max_length=255)

    def __str__(self):
        return self.divisao

class Grupo(models.Model):
    grupo = models.CharField(max_length=255)
    divisao = models.ForeignKey(Divisao, on_delete=models.CASCADE)
    responsavel = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return '%s - %s' % (self.grupo, self.divisao)

class Storage(models.Model):
    storage = models.CharField(max_length=255)
    grupo = models.ForeignKey(Grupo, on_delete=models.CASCADE)

    def __str__(self):
        return self.storage

As can be seen, I just formatted the representation string of this object/model (Group) to display the group and division to which it belongs.

I hope I’ve helped!

  • Adinanp thank you! That’s exactly what I wanted. I thought it would be a complex function like the one I tried to do but it was simple kk It helped a lot!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.