Login

Readonly Tabluar Inline

Author:
ckarrie2
Posted:
December 15, 2011
Language:
Python
Version:
1.3
Score:
5 (after 5 ratings)

An Image says more than 100 words: readonlytabularinline.png

Use editable_fields to exclude some fields from being readonly.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# admin.py

class ReadonlyTabularInline(admin.TabularInline):
    can_delete = False
    extra = 0
    editable_fields = []
    
    def get_readonly_fields(self, request, obj=None):
        fields = []
        for field in self.model._meta.get_all_field_names():
            if (not field == 'id'):
                if (field not in self.editable_fields):
                    fields.append(field)
        return fields
    
    def has_add_permission(self, request):
        return False
    

# Usage Example (admin.py)

class FixturesInline(ReadonlyTabularInline):
    model = models.Fixture
    verbose_name_plural = _('List of unpublished Fixtures')
    editable_fields = ['public']



# My models.py (a part of)

class Competition(models.Model):
    name = models.CharField(max_length=200)
    location = models.ForeignKey(Location)

class Fixture(models.Model):
    competition = models.ForeignKey(Competition)
    conference = models.BooleanField()
    home_team = models.ForeignKey(Team, related_name='hometeam')
    guest_team = models.ForeignKey(Team, related_name='guestteam')
    datetime = models.DateTimeField()
    public = models.BooleanField()
    channels = models.ManyToManyField(ChanSatMembership)
    additional_infos = models.TextField(blank=True, null=True)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

ckarrie2 (on December 16, 2011):

Works with Django SVN Rev >= 17204.

#

darkpixel (on April 18, 2013):

Replace

if (field not in self.editable_fields):

with

if (field not in self.editable_fields) and (field not in self.exclude):

to be able to use the 'exclude' property to remove fields from the inline.

#

juanjosepimentel (on August 1, 2013):

It works with Django 1.5.1

darkpixel solution works great.

I removed get_readonly_fields method and used readonly_fields tuple instead.

#

Please login first before commenting.