D
D
Dardrin2015-02-20 13:31:48
Django
Dardrin, 2015-02-20 13:31:48

What is the correct way to use ForeignKey in Django-admin fieldsets?

There is a Servers model associated 1-1 with ServersType:

class ServersType(models.Model):
    type_name = models.CharField(null=False, max_length=255)

class Servers(models.Model):
    type = models.ForeignKey(ServersType)

In the admin panel, it only works like this:
class ServersAdmin(admin.ModelAdmin):
    def get_type(self, object):
        return object.type.type_name

    get_type.admin_order_field = 'type__type_name'
    get_type.short_description = 'Type'

    fieldsets = [
        ('Other info', {'fields': ['type']}),
    ]
    list_display = ('get_type')
    list_filter = ['type__type_name']

At the same time, if I use in fieldsets - type__type_name, an error occurs
Unknown field(s) (type__type_name) specified for Servers. Check fields/fieldsets/exclude attributes of class ServersAdmin.

If just type - dropdown list ServersTypeObject.
How to display a dropdown list in a normal form?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rostislav Grigoriev, 2015-02-20
@Dardrin

Set the model to __unicode__ for the second python or __str__ for the third.
Example:

class ServersType(models.Model):
    type_name = models.CharField(null=False, max_length=255)

    def __unicode__(self):
        return self.type_name

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question