想要擴展Carl Meyer的答案,直到今天這個答案完美無缺。
我總是使用TextField
而不是CharField
(有或沒有選擇),並且在UI/API端而不是在數據庫層面施加字符限制。爲了使動態這項工作:
from django import forms
from django.contrib import admin
class BaseAdmin(admin.ModelAdmin):
"""
Base admin capable of forcing widget conversion
"""
def formfield_for_dbfield(self, db_field, **kwargs):
formfield = super(BaseAdmin, self).formfield_for_dbfield(
db_field, **kwargs)
display_as_charfield = getattr(self, 'display_as_charfield', [])
display_as_choicefield = getattr(self, 'display_as_choicefield', [])
if db_field.name in display_as_charfield:
formfield.widget = forms.TextInput(attrs=formfield.widget.attrs)
elif db_field.name in display_as_choicefield:
formfield.widget = forms.Select(choices=formfield.choices,
attrs=formfield.widget.attrs)
return formfield
我有一個型號名稱Post
其中title
,slug
& state
是TextField
S和state
有選擇。管理員定義如下:
@admin.register(Post)
class PostAdmin(BaseAdmin):
list_display = ('pk', 'title', 'author', 'org', 'state', 'created',)
search_fields = [
'title',
'author__username',
]
display_as_charfield = ['title', 'slug']
display_as_choicefield = ['state']
認爲其他人在尋找答案可能會覺得這很有用。
接受的答案是爲了modficiation只是一個領域的巨大矯枉過正!人們按照卡爾邁耶的這個答案爲簡單性的目的:http://stackoverflow.com/questions/430592/django-admin-charfield-as-textarea#431412 – andi 2014-10-30 10:05:08