I use ModelChoiceField with initial value just for display (readonly field).
But value displayed is model id and I want to display customized value that will be a concatenation of 3 fields. I've override ____str____ method but it is not applyed.
I try to make customize ModelChoiceFiedl to define label_from_instance that seems to be the way to do what I want but it is not applyed...
models.py
class Utilisateur(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
uti_ide = models.AutoField(primary_key = True)
# pro_ide = models.ForeignKey(Projet, on_delete = models.CASCADE) # related project
projets = models.ManyToManyField(Projet, through='UtilisateurProjet')
uti_nom = models.CharField("Nom", max_length=20)
uti_pre = models.CharField("Prénom", max_length=20)
uti_mai = models.CharField("Email", max_length=40)
uti_sit = models.CharField("Equipe", max_length=20, null=True, blank=True)
uti_pro = models.CharField("Fonction/profil", max_length=200, null=True, blank=True)
uti_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True)
uti_dat = models.DateTimeField("Date log",auto_now_add=True, null=True, blank=True)
log = HistoricalRecords()
#classmethod
def options_list(cls,pro_ide):
# projet = Projet.objects.get(pro_ide=pro_ide)
# utilisateurs = Utilisateur.objects.filter(pro_ide=projet.pro_ide)
utilisateurs = Utilisateur.objects.filter(projets__pro_ide=pro_ide)
the_opts_list = [(utilisateur.uti_ide, utilisateur.uti_nom+', '+utilisateur.uti_pre) for utilisateur in utilisateurs]
the_opts_list.insert(0, (None, ''))
return the_opts_list
class Meta:
db_table = 'tbl_uti'
verbose_name_plural = 'Utilisateurs'
ordering = ['uti_ide']
def __str__(self):
return f"{self.uti_nom}, {self.uti_pre} ({self.uti_mai})"
forms.py
class UtilisateurModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
print('label')
return obj.uti_nom+', '+obj.uti_pre+' ('+obj.uti_mai+')'
class UtilisateurProjetUpdateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super(UtilisateurProjetUpdateForm, self).__init__(*args, **kwargs)
# print('kwargs',self.request)
# print('projet',self.request['projet'])
# print('utilisateur',self.request['utilisateur'])
PROJETS = Projet.objects.all()
UTILISATEURS = Utilisateur.objects.all()
self.fields["pro_ide"] = forms.ModelChoiceField(queryset = PROJETS, label = "Nom projet", widget = forms.HiddenInput(), initial = Projet.objects.get(pro_ide=self.request['projet']))
self.fields["uti_ide"] = UtilisateurModelChoiceField(queryset = UTILISATEURS, label = "Nom, prénom de l'utilisateur", widget = forms.TextInput(attrs={'readonly':'readonly'}), initial = Utilisateur.objects.get(uti_ide=self.request['utilisateur']),) #,to_field_name="uti_nom"
class Meta:
model = UtilisateurProjet
fields = ('pro_ide','uti_ide',)
in forms.py under that last class Meta: you need to add:
field_classes = {
'pro_ide': UtilisateurModelChoiceField,
'uti_ide': UtilisateurModelChoiceField,
}
Related
I have a model:
class Movie (models.Model):
category = models.CharField(max_length=50, verbose_name='Kategoria filmu', default= 'unassigned', null=False, choices=category_choices)
source = models.CharField(max_length=50, verbose_name='Źródło filmu', default= 'unassigned', null=False, choices=source_choices)
promotion = models.BooleanField(default=False, verbose_name='PROMOCJA FILMU')
author = models.CharField(max_length=50, verbose_name='Nazwa influencera')
title = models.CharField(max_length=50, verbose_name='Nazwa filmu')
content = models.TextField(max_length=10000, verbose_name='HTML EMBEDED do filmu')
date_posted = models.DateTimeField(default=timezone.now)
youtube_url = models.URLField(blank=True, max_length=300)
tiktok_url = models.URLField(blank=True, max_length=300)
insta_url = models.URLField(blank=True, max_length=300)
I am passing it to the view with djnago-filter with different category choice:
views.py:
#HotTop View
class HotTopView (FilterView):
model = Movie
template_name = 'pages/hot_top.html'
filterset_class = MovieFilter
paginate_by = 6
def get_queryset(self):
category_qs = self.model.objects.filter(category="HOT-TOP")
return category_qs.order_by('-date_posted')
#Odkrycia View
class OdkryciaView (FilterView):
model = Movie
template_name = 'pages/odkrycia.html'
filterset_class = MovieFilter
paginate_by = 6
def get_queryset(self):
category_qs = self.model.objects.filter(category="ODKRYCIA")
return category_qs.order_by('-date_posted')
and my filters.py:
class MovieFilter(django_filters.FilterSet):
author = django_filters.CharFilter(label='', lookup_expr='contains', widget=TextInput(attrs={'placeholder': 'Search'}))
class Meta:
model = Movie
fields = ['author']
The question is how can i change placeholder of my serach form depending on the view (HotTop or Odkrycia). I want it to be - when i am in HotTop View -> Search in Hot Top and when i am in Odkrycia - > Search in Odkrycia
I think you could pass an argument
class MovieFilter(django_filters.FilterSet):
author = django_filters.CharFilter(label='', lookup_expr='contains', widget=TextInput(attrs={'placeholder': 'Search'}))
class Meta:
model = Movie
fields = ['author']
def __init__(self, *args, **kwargs):
placeholder = kwargs.pop('placeholder', None)
super().__init__(*args, **kwargs)
if placeholder :
self.fields['author'].widget = TextInput(attrs={'placeholder': f'Search in {placeholder}'})
and then in the views you can use get_filterset_kwargs method to pass the view name.
#HotTop View
class HotTopView(FilterView):
...
def get_filterset_kwargs(self):
kwargs = super(HotTopView, self).get_filterset_kwargs()
kwargs['placeholder'] = "Hot Top"
return kwargs
...
the other view:
#Odkrycia View
class OdkryciaView(FilterView):
...
def get_filterset_kwargs(self):
kwargs = super(OdkryciaView, self).get_filterset_kwargs()
kwargs['placeholder'] = "Odkrycia"
return kwargs
...
I hope that answers your question.
I have already posted (see link below) to 'valid' my ER diagram.
I try to develop a form based on 'trought' model with nested inlineformset.
It works when I define fields in the UtilisateurCreateView class but I want to customize the 'trought' parent's form to be able to:
set initial pro_ide value with value send by GET
hidden this pro_ide field
customize uti_ide field label
So I define a UtilisateurProjetCreateForm based on the 'throught' model like I'm used to do but I got an error:
Cannot assign "'Slater, Kelly (k.slater#surf.com)'": "UtilisateurProjet.uti_ide" must be a "Utilisateur" instance.
moreover, as this form is based on 'throught' model, I am not sure I should define forms.ChoiceField...
models.py
class Projet(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
pro_ide = models.AutoField(primary_key = True)
# utilisateurs = models.ManyToManyField(Utilisateur, through='UtilisateurProjet')
pro_nom = models.IntegerField("Nom du projet")
pro_log = models.CharField("Log utiisateur", max_length=20, null=True, blank=True)
pro_dat = models.DateTimeField("Date log",auto_now_add=True)
pro_act = models.IntegerField("Projet en cours ?", null=True, blank=True)
class Meta:
db_table = 'tbl_pro'
verbose_name_plural = 'Projets'
ordering = ['pro_ide']
permissions = [
('can_add_project','Can add project'),
]
def __str__(self):
return f"{self.pro_nom}"
class Utilisateur(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
uti_ide = models.AutoField(primary_key = True)
# pro_ide = models.ForeignKey(Projet, on_delete = models.CASCADE) # related project
projets = models.ManyToManyField(Projet, through='UtilisateurProjet')
uti_nom = models.CharField("Nom", max_length=20)
uti_pre = models.CharField("Prénom", max_length=20)
uti_mai = models.CharField("Email", max_length=40)
uti_sit = models.CharField("Equipe", max_length=20, null=True, blank=True)
uti_pro = models.CharField("Fonction/profil", max_length=200, null=True, blank=True)
uti_dem_dat = models.DateTimeField("Date demande",auto_now_add=True, null=True, blank=True)
uti_val = models.IntegerField("Demande validée ?", null=True, blank=True)
uti_val_dat = models.DateTimeField("Date validation",null=True, blank=True)
uti_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True)
uti_dat = models.DateTimeField("Date log",auto_now_add=True, null=True, blank=True)
class Meta:
db_table = 'tbl_uti'
verbose_name_plural = 'Utilisateurs'
ordering = ['uti_ide']
def __str__(self):
return f"{self.uti_nom}, {self.uti_pre} ({self.uti_mai})"
class UtilisateurProjet(models.Model):
_safedelete_policy = SOFT_DELETE_CASCADE
pro_uti_ide = models.AutoField(primary_key = True)
uti_ide = models.ForeignKey(Utilisateur, on_delete=models.CASCADE)
pro_ide = models.ForeignKey(Projet, on_delete=models.CASCADE)
class Meta:
db_table = 'tbl_pro_uti'
class Application(SafeDeleteModel):
_safedelete_policy = SOFT_DELETE_CASCADE
app_ide = models.AutoField(primary_key = True)
# uti_ide = models.ForeignKey(Utilisateur, on_delete = models.CASCADE) # related utilisateur
pro_uti_ide = models.ForeignKey(UtilisateurProjet, on_delete = models.CASCADE) # related utilisateur-projet
app_app_nom = models.IntegerField("Nom application", null=True, blank=True)
app_dro = models.IntegerField("Droit sur application", null=True, blank=True)
app_sta = models.IntegerField("Statut (création/Modification/Suppression", null=True, blank=True)
app_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True)
app_dat = models.DateTimeField("Date log",auto_now_add=True, null=True, blank=True)
class Meta:
db_table = 'tbl_app'
verbose_name_plural = 'Applications'
ordering = ['app_ide']
views.py
# https://stackoverflow.com/questions/29981690/django-form-validation-on-class-based-view
class UtilisateurCreateView(FormView):
template_name = 'project/utilisateurprojet_form.html'
form_class = UtilisateurProjetCreateForm
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
if self.request.POST:
data["utilisateur"] = self.request.user.username # nom de l'utilisateur connecté
data["projet"] = get_object_or_404(Projet, pro_ide = self.request.GET['projet'])
data["application"] = ApplicationFormset(self.request.POST)
else:
data["application"] = ApplicationFormset()
return data
def form_valid(self, form):
context = self.get_context_data()
application = context["application"]
self.object = form.save(commit=False)
self.object.uti_log = context["utilisateur"]
self.object.save()
if application.is_valid():
application.instance = self.object
application.save()
return super().form_valid(form)
def get_success_url(self):
return reverse("project:index")
forms.py
ApplicationFormset = inlineformset_factory(
UtilisateurProjet, Application,
fields=('app_app_nom','app_dro'),
widgets={
'app_app_nom': forms.Select(choices=NAME),
'app_dro': forms.Select(choices=ACCESS)
},
extra=3,
can_delete=True,
)
class UtilisateurProjetCreateForm(forms.ModelForm):
PROJETS = [(Projet.objects.get(pro_ide=1),'Coverage Africa'),]
UTILISATEURS = [(Utilisateur.objects.get(uti_ide=1),'Slater'),]
pro_ide = forms.ChoiceField(label = "Nom projet", widget = forms.Select, choices = PROJETS, initial = Projet.objects.get(pro_ide=1), disabled=True)
uti_ide = forms.ChoiceField(label = "Nom, prénom de l'utilisateur", widget = forms.Select, choices = UTILISATEURS)
class Meta:
model = UtilisateurProjet
fields = ('pro_ide','uti_ide')
related post
I had to use ModelChoiceFiled in my ModelForm:
class UtilisateurProjetCreateForm(forms.ModelForm):
PROJETS = Projet.objects.all()
UTILISATEURS = Utilisateur.objects.all()
pro_ide = forms.ModelChoiceField(queryset = PROJETS, label = "Nom projet", widget = forms.Select, initial = Projet.objects.get(pro_ide=1))
uti_ide = forms.ModelChoiceField(queryset = UTILISATEURS, label = "Nom, prénom de l'utilisateur", widget = forms.Select)
class Meta:
model = UtilisateurProjet
fields = ('pro_ide','uti_ide')
I'm new on Django Rest Framework and when I want to POST data I get a error: KeyError: 'id_area' I do not know what I'm doing wrong. Here's my code:
in my models.py
class Area(models.Model):
id_area = models.AutoField(primary_key=True)
APM = 'apm'
BUSINESS = 'business'
DESARROLLO = 'desarrollo'
SISTEMAS = 'sistemas'
ATENTUSIANOS_CHOICES = (
(APM, 'Apm'),
(BUSINESS, 'Business'),
(DESARROLLO, 'Desarrollo'),
(SISTEMAS, 'Sistemas'),
)
nombre = models.CharField(max_length=255, choices=ATENTUSIANOS_CHOICES)
class Meta:
verbose_name = 'Área'
verbose_name_plural = 'Áreas'
def __str__(self):
return self.nombre
class Atentusiano(models.Model):
id_atentusiano = models.AutoField(primary_key=True)
nombre = models.CharField(max_length=255, blank=False, null=False)
apellido = models.CharField(max_length=255, blank=False, null=False)
correo = models.CharField(max_length=255, blank=False, null=False, unique=True)
anexo = models.CharField(max_length=255, blank=True, null=True)
area = models.ForeignKey(Area, related_name='areas', on_delete=models.CASCADE)
class Meta:
verbose_name = 'Atentusiano'
verbose_name_plural = 'Atentusianos'
ordering = ['nombre']
def __str__(self):
return self.nombre + ' ' + self.apellido
in my serializers.py
class AreaSerializer(serializers.ModelSerializer):
areas = serializers.CharField(read_only=True)
class Meta:
model = Area
fields = ('id_area', 'nombre', 'areas')
class AtentusianoSerializer(serializers.ModelSerializer):
atentusianos = serializers.CharField(read_only=True)
area = serializers.CharField(source='area.nombre', read_only=True)
id_area = serializers.CharField(source='area.id_area')
class Meta:
model = Atentusiano
fields = ['id_atentusiano', 'nombre', 'apellido', 'correo', 'anexo', 'id_area', 'area', 'atentusianos']
def create(self, validated_data):
area_data = validated_data.pop('id_area')
area = models.Area.objects.create(**area_data)
atentusiano = models.Atentusiano.objects.create(area=area, **validated_data)
return atentusiano
And in my views.py
class AtentusianoView(viewsets.ModelViewSet):
queryset = Atentusiano.objects.all()
serializer_class = AtentusianoSerializer
class AreaView(viewsets.ModelViewSet):
queryset = Area.objects.all()
serializer_class = AreaSerializer
The problem is that when I want to Post data, for example:
{
"nombre": "name",
"apellido": "lastname",
"correo": "email#gmail.com",
"anexo": "1364",
"id_area": "1"
}
i got this error area_data = validated_data.pop('id_area')
KeyError: 'id_area'
I need help please
you should pop like this,
class AtentusianoSerializer(serializers.ModelSerializer):
.....
.....
class Meta:
model = Atentusiano
fields = ['id_atentusiano', 'nombre', 'apellido', 'correo', 'anexo', 'id_area', 'area', 'atentusianos']
def create(self, validated_data):
id_area = validated_data.pop('area')['id_area'] # here the correction
area = Area.objects.create(id_area=id_area) # an additional correction
atentusiano = Atentusiano.objects.create(area=area, **validated_data)
return atentusiano
EDIT: As id_area value, you are passing a string instead of an integer which will through another error. Also not,
area = models.Area.objects.create(**area_data)
it should be,
area = Area.objects.create(id_area=id_area)
forms.py
class MySelect(forms.Select):
def __init__(self, *args, **kwargs):
self.variations = kwargs.pop('variations')
super(MySelect, self).__init__(*args, **kwargs)
def render_option(self, selected_choices, option_value, option_label):
return '<option whatever>...</option>'
class CartItemForm(forms.ModelForm):
class Meta:
model = CartItem
fields = (
'variation',
'width',
'height',
'quantity',
)
widgets = {
'variation': MySelect(variations=self.variation_query)
}
def __init__(self, *args, **kwargs):
product = kwargs.pop('product')
try:
cart = kwargs.pop('cart')
self.cart = cart
except:
pass
super().__init__(*args, **kwargs)
variation_field = self.fields['variation']
variation_field.queryset = Variation.objects.filter(
product=product
)
self.variation_query = Variation.objects.filter(
product=product
)
def save(self):
cart_item = super().save(commit=False)
cart_item.cart = self.cart
cart_item.save()
return cart_item
Below is where you have to pay attention to.
(in Meta class)
widgets = {
'variation': MySelect(variations=self.variation_query)
}
self.variation_query is from __init__.
How can I do this?
models.py
class CartItem(models.Model):
cart = models.ForeignKey("Cart")
variation = models.ForeignKey(Variation)
# 벽화 너비
width = models.PositiveIntegerField(
default=1,
validators=[MinValueValidator(1)],
)
class Product(TimeStampedModel):
name = models.CharField(max_length=120, unique=True)
slug = models.SlugField(null=True, blank=True)
description = models.TextField(max_length=400, blank=True)
is_active = models.BooleanField(default=True)
place_category = models.ForeignKey(
"PlaceCategory",
related_name="products_by_place", # category.products_by_place.all()
)
subject_category_set = models.ManyToManyField(
"SubjectCategory",
related_name="products_by_subject", # category.products_by_subject.all()
)
# 벽화 높이
height = models.PositiveIntegerField(
default=1,
validators=[MinValueValidator(1)],
)
quantity = models.PositiveIntegerField(
default=1,
validators=[MinValueValidator(1)],
)
class Variation(TimeStampedModel):
COLOR_CHOICES = (
('black', '흑백'),
('single', '단색'),
('multi', '컬러'),
)
price = models.DecimalField(
decimal_places=0,
max_digits=15,
blank=True,
null=True,
)
product = models.ForeignKey(Product)
color = models.CharField(
max_length=10,
choices=COLOR_CHOICES,
)
is_active = models.BooleanField(default=True)
That's not a thing you would do in Meta. You need to do the whole thing in __init__.
You're already doing that in fact, so I don't know why you want to override Meta at all.
In my case change form load very slow In Admin interface because a one_to_one field "disk" in SeverHasDisk Model in models.py. There is a disk field in ServerHasDiskInLine in admin.py. It works fine when I exclude "Disk" field from ServerHasDiskInLine in admin.py.
Is there a way to increase the performance by using a form class for ServerHasDiskInLine(admin.TabularInline)
or something else?
Models.py
#Models.py
class Server(models.Model):
hostname = models.CharField(max_length=64, unique=True, db_index=True)
description = models.TextField(max_length=255, blank=True, null=True)
note = models.TextField(max_length=255, blank=True, null=True)
numberOfCpu = models.IntegerField(default=1) # vCPU or HThread core
cpuClockRate = models.CharField(max_length=255) # Mhz
virtualization = models.CharField(max_length=255, blank=True, null=True)
ram = models.FloatField() # Go
vnc = models.IntegerField(blank=True, null=True, unique=True)
monitored = models.BooleanField(default=True)
dns = models.CharField(max_length = 255, blank=True, verbose_name= "DNS")
ansible = models.CharField(max_length = 255, blank=True, verbose_name= "Ansible")
# --------------Relations -----------------
# backup = models.ForeignKey('self', name='server_backup', related_name='backup', blank=True, null=True)
hypervisor = models.ForeignKey('self', name='server_hypervisor', related_name='hypervisor', blank=True, null=True)
operatingSystem = models.ForeignKey(OperatingSystem)
module = models.ForeignKey(Module, blank=True, null=True)
project = models.ForeignKey(Project, blank=True, null=True)
customer = models.ForeignKey(Customer, blank=True, null=True)
environment = models.ForeignKey(Environment, blank=True, null=True)
site = models.ForeignKey(Site, blank=True, null=True)
status = models.ForeignKey(ServerStatus, blank=True, null=True )
class Meta:
ordering = ('hostname',)
unique_together = ('hostname', 'site',)
class VolumeGroup(models.Model):
name = models.CharField(max_length=64, unique=True, db_index=True)
size = models.IntegerField() # Go
class Meta:
ordering = ('name',)
def __unicode__(self):
return "%s (%s Go)" % (self.name, self.size)
class LogicalVolume(models.Model):
# ------------------ Fields ---------------
name = models.CharField(max_length=64, unique=True, db_index=True)
size = models.IntegerField() # Go
note = models.TextField(max_length=255, blank=True, null=True)
# --------------Relations -----------------
volumeGroup = models.ForeignKey(VolumeGroup)
class Meta:
ordering = ('name',)
unique_together = ('volumeGroup', 'name')
def __unicode__(self):
return "%s (%s Go) on VG <%s>" % (self.name, self.size, self.volumeGroup.name)
class ServerHasDisk(models.Model):
# ------------------ Fields ---------------
mountPoint = models.CharField(max_length=255)
# --------------Relations -----------------
server = models.ForeignKey(Server, related_name='serverDisks')
disk = models.OneToOneField(LogicalVolume)
class Meta:
ordering = ('mountPoint',)
unique_together = ('server', 'disk')
def __unicode__(self):
return "Srv [%s]: %s ==> <%s> on VG <%s>" % (self.server.hostname, self.mountPoint, self.disk.name, self.disk.volumeGroup.name)
Admin.py
class ServerHasDiskInline(admin.TabularInline):
model = ServerHasDisk
extra = 0
# formset = MyFormSet
classes = ('grp-collapse grp-open',)
#exclude = ['disk']
class ServerHasRoleInline(admin.TabularInline):
model = ServerHasRole
extra = 0
fk_name = 'server'
classes = ('grp-collapse grp-open',)
class IpInline(admin.TabularInline):
model = IP
extra = 0
classes = ('grp-collapse grp-open',)
class BkSrvInline(admin.TabularInline):
model = ServerIsBackupedOn
fk_name = 'server'
extra = 0
classes = ('grp-collapse grp-open',)
class ServerAdmin(admin.ModelAdmin):
change_list_template = "admin/change_list_filter_sidebar.html"
list_display = ('hostname', 'get_project_name', 'get_module_name', 'get_environment_name', 'get_customer_name', 'get_os_name', 'get_site_name', 'get_ip_name', 'get_bk_hostname', 'get_role_name', 'description','note','get_dns','get_status','get_ansible')
list_filter = ('project__name', 'module__name', 'environment__name', 'customer__name', 'site__name', 'operatingSystem__name', 'serverRoles__role__name', 'serverIps__address')
list_per_page = 25
search_fields = ('hostname', 'project__name', 'module__name', 'environment__name', 'serverIps__address', 'serverRoles__role__name', 'note')
inlines = (ServerHasDiskInline,ServerHasVolumeGroupInline,ServerHasRoleInline, IpInline, BkSrvInline)
#related_search_fields={
#'disk': ( 'name', ),
#}
def get_project_name(self, o):
if o.project is None:
return "N/A"
else:
return o.project.name
get_project_name.admin_order_field = 'project'
get_project_name.short_description = 'Project'
def get_dns(self, o):
if o.dns is None:
return "N/A"
else:
return o.dns
get_dns.admin_order_field = 'dns'
get_dns.short_description = 'DNS'
def get_ansible(self, o):
if o.ansible is None:
return "N/A"
else:
return o.ansible
get_ansible.admin_order_field = 'ansible'
get_ansible.short_description = 'Ansible'
def get_module_name(self, o):
if o.module is None:
return "N/A"
else:
return o.module.name
get_module_name.admin_order_field = 'module'
get_module_name.short_description = 'Module'
def get_customer_name(self, o):
if o.customer is None:
return "N/A"
else:
return o.customer.name
get_customer_name.admin_order_field = 'customer'
get_customer_name.short_description = 'Customer'
def get_os_name(self, o):
if o.operatingSystem is None:
return "N/A"
else:
return o.operatingSystem.name
get_os_name.admin_order_field = 'operatingsystem'
get_os_name.short_description = 'OS'
def get_environment_name(self, o):
if o.environment is None:
return "N/A"
else:
return o.environment.name
get_environment_name.admin_order_field = 'environment'
get_environment_name.short_description = 'Environment'
def get_status(self, o):
if o.status is None:
return "N/A"
else:
return o.status.status
get_status.admin_order_field = 'status'
get_status.short_description = 'Status'
def get_site_name(self, o):
if o.site is None:
return "N/A"
else:
return o.site.name
get_site_name.admin_order_field = 'site'
get_site_name.short_description = 'Site'
def get_ip_name(self, o):
return ", ".join([
'%s' % ('../ip', k.id, k.address)
for k in o.serverIps.all()
])
# return ", ".join([k.address for k in o.serverIps.all()])
get_ip_name.admin_order_field = 'serverIps'
get_ip_name.short_description = 'IP'
get_ip_name.allow_tags = True
def get_bk_hostname(self, o):
return ", ".join([
'%s' % ('../server', k.backupServer.id, k.backupServer.hostname)
for k in o.serverBackuped.all()
])
# return '%s' % ('../project', o.project.id, o.project.name)
get_bk_hostname.admin_order_field = 'serverBackuped'
get_bk_hostname.short_description = 'Bk Srv'
get_bk_hostname.allow_tags = True
def get_role_name(self, o):
return ", ".join([k.role.name for k in o.serverRoles.all()])
get_role_name.admin_order_field = 'serverRoles'
get_role_name.short_description = 'Role'
Here is quick solution.
I have just added an attribute to ServerHasDiskInLine class in Admin.py
raw_id_fields = ("disk",) so New class is
class ServerHasDiskInline(admin.TabularInline):
model = ServerHasDisk
raw_id_fields = ("disk",)
extra = 0
classes = ('grp-collapse grp-open',)
#exclude = ['disk']