Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin form, field instead of object in foreign key

Tags:

python

django

Im using a forigen key to reference another object from my parent object. However when i go to the drop down list created by django admin, i get the object name instead of the field value. how can i add the field value to the form instead?

object instead of field name

admin.py

    from django.contrib import admin

from .models import Maintenance
from .models import MaintenanceType
from .models import ServiceType

# Register your models here.


class MaintenanceAdmin(admin.ModelAdmin):
    list_display = ('Title','Impact','Service','Description','StartTime','EndTime',)
    list_editable = ('Title','Impact','Service','Description','StartTime','EndTime',)


admin.site.register(Maintenance, MaintenanceAdmin)

class MaintenanceTypeAdmin(admin.ModelAdmin):
    list_display = ('Type',)
    list_editable = ('Type',)

admin.site.register(MaintenanceType, MaintenanceTypeAdmin)

class ServiceTypeAdmin(admin.ModelAdmin):
    list_display = ('Service','Service',)
    list_editable = ('Service','Service',)

admin.site.register(ServiceType, ServiceTypeAdmin)

models.py

from django.db import models

# Create your models here.

class MaintenanceType(models.Model):
    Type = models.CharField(max_length=200)

    class Meta:
                verbose_name = "Planned Maintenance Types"
                verbose_name_plural = "Planned Maintenance Types"

class ServiceType(models.Model):
    Service = models.CharField(max_length=200)

    class Meta:
                verbose_name = "Service Types"
                verbose_name_plural = "Service Types"                

class Maintenance(models.Model):
    Title = models.CharField(max_length=200)
    Impact = models.ForeignKey(MaintenanceType)
    Service = models.ForeignKey(ServiceType)
    Description = models.TextField()
    StartTime = models.DateTimeField()
    EndTime = models.DateTimeField()

    class Meta:
                verbose_name = "Planned IT Maintenance"
                verbose_name_plural = "Planned IT Maintenance"                
like image 675
AlexW Avatar asked May 11 '16 16:05

AlexW


People also ask

How do you make a field required in Django admin?

Just define a custom form, with your required field overridden to set required=True, and use it in your admin class.

How do you make a field non mandatory in Django admin?

The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).


1 Answers

Implement __str__ in the MaintenanceType model, which should return a string in whatever formatting you wish to appear in the drop down (and anywhere else actually).

It appears that you simply need to return self.Type.

like image 179
DeepSpace Avatar answered Sep 30 '22 17:09

DeepSpace