Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin StackedInline customisation

I have a Django database of books, with attached transactions. In the admin interface, on each book page, I'd like to show the transactions attached to each book.

Ideally, this should be read-only, with no ability to add or delete transactions. I'd like to show only some of the model's fields.

In models.py:

class Book(models.Model):
    title = models.CharField(max_length=400)
class Transaction(models.Model):
    id = models.IntegerField(primary_key=True)
    book = models.ForeignKey(Book)
    user = models.ForeignKey(User)
    transaction_type = models.IntegerField(choices=TRANSACTION_TYPES)
    ipaddress = models.IPAddressField(null=True, blank=True)
    transaction_date = models.DateTimeField()
    date_added = models.DateTimeField(auto_now_add=True) 
    class Meta:
        get_latest_by = 'transaction_date'
        ordering = ('-transaction_date',)

In admin.py:

class TransactionInline(admin.StackedInline):
    model = Transaction
    readonly_fields = ['user', 'transaction_type', 'transaction_date']
    verbose_name = 'Transaction'
    verbose_name_plural = 'Book history'
class BookAdmin(admin.ModelAdmin):
    fieldsets = [ (None, {'fields': ['title'}) ]
    inlines = [ TransactionInline, ]

I have several questions, all related to the fact that transactions are conceptually read-only.

  1. How can I disable the 'add new' link for transactions?
  2. How can I only show the fields I care about - user, transaction_type and transaction_date - and hide the others?

Also: the header is currently "Book History -- Transaction: Transaction object". How can I show something friendlier than 'Transaction object'?

Please let me know if this should be split out into separate questions!

Thanks.

like image 514
AP257 Avatar asked Feb 03 '11 19:02

AP257


1 Answers

1: set max_num to 0
http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#model-formsets-max-num

2: specify the fields attribute http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fields

Also: override the __unicode__ method in your model
http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.unicode

like image 149
Yuji 'Tomita' Tomita Avatar answered Sep 20 '22 05:09

Yuji 'Tomita' Tomita