Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin: how to display properties defined on model in an inline?

This is a follow-up to this question. How do I display properties defined on a child model in an inline on the parent? To illustrate, I have this model:

class UserProfile(models.Model):     user = models.ForeignKey(User, unique=True, primary_key=True, related_name='profile')     ...     @property     def age(self):         if self.birthday is None:             return None          td = datetime.date.today() - self.birthday         return td.days / 365 

Question is: how do I show 'age' in an inline on User? This is what I have:

class UserProfileInline(admin.StackedInline):     model = UserProfile     fk_name = 'user'     max_num = 1     fieldsets = [         ('Demographics', {'fields': ['birthday', 'age']}),     ] 

I've tried a few things like this, including 'age()', defining a 'get_age' getter for the Inline, etc. They result in some version of this error:

ImproperlyConfigured: 'UserProfileInline.fieldsets[1][1]['fields']' refers to field 'age' that is missing from the form. 
like image 700
Joe Avatar asked Aug 09 '10 15:08

Joe


People also ask

What is __ Str__ in Django model?

The __str__() method is called whenever you call str() on an object. Django uses str(obj) in a number of places. Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object.

What is @property in Django model?

What is @property in Django? Here is how I understand it: @property is a decorator for methods in a class that gets the value in the method. But, as I understand it, I can just call the method like normal and it will get it.

What is UserAdmin in Django?

Django uses UserAdmin to render the nice admin look for User model. By just using this in our admin.py -file, we can get the same look for our model. from django.contrib.auth.admin import UserAdmin admin.site.register(MyUser, UserAdmin)

What is Admin ModelAdmin in Django?

One of the most powerful parts of Django is the automatic admin interface. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin's recommended use is limited to an organization's internal management tool.


1 Answers

Add the field to both the readonly_fields tuple and fieldsets field as well.

Note this only works in Django 1.2+.

like image 135
Daniel Roseman Avatar answered Oct 02 '22 11:10

Daniel Roseman