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)