jwe*_*nga 5 django field admin
我想通过设置editable = False来隐藏管理员中的slug字段,但每次我这样做时都会收到以下错误:
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
Run Code Online (Sandbox Code Playgroud)
不知道为什么会这样
我不能说出你的确切错误,但这对我有用...
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
Run Code Online (Sandbox Code Playgroud)
当模型保存时,这会将你甩掉一个slug字段.
只需在ModelAdmin中省略自动填充内容即可.
我在管理员中运行没有问题.
我的解决方案不仅隐藏了slug字段,还允许在尚未保存时更换slug.问题是所使用的字段prepopulated_fields必须是格式,但如果只是readonly则不存在.prepopulated_fields如果未设置readonly,则仅通过设置来解决此问题.
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 {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9044 次 |
| 最近记录: |