I
I
Ilya2015-03-10 00:20:43
Django
Ilya, 2015-03-10 00:20:43

How to view the id of an object in the admin panel?

Based on what the official tutorial says, django automatically assigns an id for each model object.
When creating a template, {{ object.id }} can be used there. And everything works.
But I want the id to be displayed in the admin.
fields = ['id'] doesn't work.
Here is the model code:

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=20)
    votes = models.IntegerField(default=0)

Here is the code in admin.py
class ChoiceInLine(admin.TabularInline):
    model = Choice
    extra = 3
    fields = ['choice_text', 'votes']

So everything works, but if you use fields = ['choice_text', 'votes', 'id'], then when the page loads, I get a KeyError.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey K, 2015-03-10
@Quirel

readonly_fields = ['id']

S
Salavat Sharapov, 2015-03-10
@desperadik

Все что вы вписываете в fields - подразумевает, что вы описываете какие поля можно редактировать. Естественно, если Вы впишите туда id(permanent key, identificator) получите KeyError.

A
Alexander Pinkevich, 2015-03-10
@pinkevich

в модели добавьте метод ниже, и будет выводится в админке Obj: 1, Obj: 2...

def __str__(self):
    return 'Obj: {}'.format(self.id)

если нужно больше чем в __str__, то юзайте fields, например:
fields = ['__str__', 'choice_text', 'votes']

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question