How it works...

If you add a few products with photos, and then look at the product administration list in the browser, it will look similar to the following screenshot:

The list_display property is usually used to define the fields to display in the administration list view; for example, title and price are fields of the Product model. Besides the normal field names, though, the list_display property also accepts the following:

  • A function, or another callable
  • The name of an attribute of the admin model
  • The name of an attribute of the model
In Python, callable is a function, method, or class that implements the __call__() method. You can check whether a variable is callable by using the callable() function.

When using callables in list_display, each one will get the model instance passed as the first argument. Therefore, in our example, we have defined the get_photo() method in the model admin class, and that receives the Product instance as obj. The method tries to get the first ProductPhoto object from the many-to-one relationship, and, if it exists, it returns HTML generated from the include template, with the <img> tag linked to the detail page for  Product.

You can set several attributes for the callables that you use in list_display. The short_description attribute of the callable defines the title shown at the top of the column, for instance. When content will not sort naturally, the admin_order_field attribute can be set to another field name, optionally using a hyphen prefix to indicate a reversed sort order.

Finally, the Price field is made editable by including it in the list_editable setting, and, as there are editable fields, a Save button is introduced at the bottom, to save the whole list of products.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.210.91