Readonly Tabluar Inline

 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. Read only form & model field by StanislavKraev 2 years, 9 months ago
  2. Readonly admin fields by peritus 5 years, 8 months ago
  3. Replace model select widget in admin with a readonly link to the related object by ekellner 5 years, 7 months ago
  4. Readonly fields on Form/Modelform by Killarny 5 years, 1 month ago
  5. ReadOnlyWidget by guettli 4 years, 8 months 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.

#

(Forgotten your password?)