Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide fields in Django admin

I'm tying to hide my slug fields in the admin by setting editable=False but every time I do that I get the following error:

KeyError at /admin/website/program/6/
Key 'slug' not found in Form
Request Method: GET
Request URL:    http://localhost:8000/admin/website/program/6/
Exception Type: KeyError
Exception Value:    
Key 'slug' not found in Form
Exception Location: c:\Python26\lib\site-packages\django\forms\forms.py in __getitem__, line 105
Python Executable:  c:\Python26\python.exe
Python Version: 2.6.4

Any idea why this is happening

like image 690
jwesonga Avatar asked Apr 21 '10 18:04

jwesonga


2 Answers

I can't speak to your exact error but this worked for me...

from django.template.defaultfilters import slugify
# Create your models here.

class Program(models.Model):
    title=models.CharField(max_length=160,help_text="title of the program")
    description=models.TextField(help_text="Description of the program")
    slug=models.SlugField(max_length=160,blank=True,editable=False)

    def __unicode__ (self):
        return self.title

    class Meta:
        verbose_name="KCDF Program"
        verbose_name_plural="KCDF Programs"

    def save(self):
        self.slug = slugify(self.title)
        super(Program,self).save()

    def get_absolute_url(self):
        return "/program/%s/" % self.slug

That will whip you up a slug field when the model is saved.

Just leave out the auto-populate thing in the ModelAdmin.

I had that running in the admin without a problem.

like image 93
Brant Avatar answered Sep 23 '22 01:09

Brant


My solution does not just hide the slug field, but allows changing the slug when not yet saved. The problem is that the fields used in prepopulated_fields, must be in the form, but they aren't there if readonly. This is solved by only setting prepopulated_fields if readonly is not set.

class ContentAdmin(admin.ModelAdmin):
    def get_readonly_fields(self, request, obj=None):
        if obj:
            return ('slug',)
        return ()
    def get_prepopulated_fields(self, request, obj=None):
        if not obj:
            return {'slug': ('title',)}
        return {}
like image 22
Jan Schär Avatar answered Sep 27 '22 01:09

Jan Schär