I've got the exact same problem than him : Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?
I want to see the question on the answer admin. I did the same thing than in the answer but got this error:
'Answer' object has no attribute 'question'
here is my code(question can have many possible answer):
class Question(models.Model):
question = models.CharField(max_length=255)
class Answer(models.Model):
question = models.ForeignKey('Question')
answer = models.CharField(max_length=255)
my admin:
class AnswerAdmin(admin.ModelAdmin):
model = Answer
list_display = ['answer', 'get_question', ]
def get_question(self, obj):
return obj.question.question
admin.site.register(Answer, AnswerAdmin)
Not sure why this wouldn't work, but an alternative solution would be to override the __unicode__()
method in Question
(or __str__()
if you're using Python3), which is what is displayed when you include a ForeignKey
field in list_display
:
class Question(models.Model):
question = models.CharField(max_length=255)
def __unicode__(self):
return self.question
class Answer(models.Model):
question = models.ForeignKey('Question')
answer = models.CharField(max_length=255)
class AnswerAdmin(admin.ModelAdmin):
model = Answer
list_display = ['answer', 'question', ]
Docs: https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With