Customize Django Admin

2

I have 2 classes, one that is the Division and another that is Group.

In the group I have the FK for division.

I want to register a Storage in the Django Admin and select the Group I want the group to appear and divide it into 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 it the following way, but without success

widgets.py

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)
    
asked by anonymous 22.01.2018 / 16:37

1 answer

2

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

Ifyes,whatIdidtoarriveatthisresultismuchsimplerthanitseems,see:

Justtypethe__str__methodinyourtemplates.Thismethodiscallingwheneveryoucallstr(objeto).Djangousesthismethodinseveralplacesandmostnotably,todisplayanobjectintheDjangoadminsite,whichiswhereyouwanttoviewthiscase.

Formoredetails, read .

The example below was 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) so that it can display the group and the division it belongs to.

I hope I have helped!

    
24.01.2018 / 16:24