Question

I'm new to django and I'm playing a little bit with it. But I have a problem, and I'm unable to find the solution.

Here is my code :

admin.py

from django.contrib import admin
from surveyApp.models import survey, answer

admin.site.register(survey)

class answerAdmin(admin.ModelAdmin):
    list_display = ('answer_text', 'survey', 'category', 'ans_date', survey.get_exp())

admin.site.register(answer, answerAdmin)

models.py

from django.db import models

Create your models here.                                                                                                                                                                                   

class survey (models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    exp_date = models.DateTimeField('date expired')

    def __str__(self):
        return self.question
    def get_exp(self):
        return self.exp_date



class answer (models.Model):
    FB_CAT = (
        ('N', 'Network'),
        ('D', 'Display'),
        ('F', 'Function'),
        )
    survey = models.ForeignKey(survey)
    answer_text = models.CharField(max_length=200)
    category = models.CharField(max_length=1, choices=FB_CAT)
    ans_date = models.DateTimeField('date answered')

    def __str__(self):
        return self.answer_text

So, I want to add in my list_display (class answerAdmin) the exp_date of the survey.

How can I access it ?

Now this code gives me an Error : 'str' object has no attribute 'exp_date'.

I already try :

survey.get_exp()
'survey.exp_date'
survey.exp_date

But errors... I'm sure there is something simple to do it.

I thank you all in advance for the time you will take for my question.

Paul

Was it helpful?

Solution

Just add a callable to your AnswerAdmin:

from django.contrib import admin
from surveyApp.models import survey, answer

admin.site.register(survey)

class AnswerAdmin(admin.ModelAdmin):
    list_display = ('answer_text', 'survey', 'category', 'ans_date', 'exp_date')

    def exp_date(self, obj):
        return obj.survey.exp_date
    exp_date.short_description = 'Exp Date'

    admin.site.register(answer, answerAdmin)

Also, just as general Django advice: models (or any other classes) are usually capitalized. Thus:

class Survey (models.Model):
    ....
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top