Dec 16, 2011

Readonly Tabluar Inline

# 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)

No comments: