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)
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!!
– Bianca C.