我想在django管理页面中禁用(首选)或隐藏'slug'字段。我从django源代码“prepopulated_fields crashes with get_readonly_fields”中发现了bug,但它实际上并没有解决问题。
我正在使用django 1.5.5
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=140, unique=True)
slug = models.SlugField(max_length=140, unique=True)
...
from django.contrib import admin
from blog.models import Post
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
readonly_fields = ('slug',)
...
KeyError at /admin/blog/post/2/
u"Key 'slug' not found in Form"
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/blog/post/2/
Django Version: 1.5.5
Exception Type: KeyError
Exception Value: u"Key 'slug' not found in Form"
Exception Location: /home/XXXXXX/django_projects/virtualenvs/myenv27/local/lib/python2.7/site-packages/django/forms/forms.py in __getitem__, line 111
Python Executable: /home/XXXXXX/django_projects/virtualenvs/myenv27/bin/python
Python Version: 2.7.3
这可能是非常简单的问题,但我找不到工作解决方案。也许有人知道这个问题的好方法。
感谢。
答案 0 :(得分:0)
未经测试,但应该关闭:
class PostAdmin(admin.ModelAdmin):
...
def __init__(self, *args, **kwargs):
super(PostAdmin, self).__init__(*args, **kwargs)
if not self.instance:
self.prepopulated_fields = {'slug': ('title',)}
def get_readonly_fields(self, request, obj=None):
fields = []
if obj:
fields += ['slug']
return fields