Muốn mở rộng câu trả lời của Carl Meyer, hoạt động hoàn hảo cho đến ngày này.
Tôi luôn sử dụng TextField
thay vì CharField
(có hoặc không có lựa chọn) và áp đặt giới hạn ký tự trên giao diện người dùng/API thay vì ở cấp DB. Để làm việc này tự động:
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
Tôi có một tên mô hình Post
nơi title
, slug
& state
là TextField
s và state
có sự lựa chọn.Định nghĩa quản trị trông giống như:
@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']
Những người khác tìm kiếm câu trả lời có thể thấy điều này hữu ích.
Câu trả lời được chấp nhận là quá mức cần thiết cho mục đích modficiation chỉ là một trường! NHÂN DÂN THEO D THI này ĐÁP ỨNG bởi Carl Meyer CHO MỤC ĐÍCH ĐƠN GIẢN: http://stackoverflow.com/questions/430592/django-admin-charfield-as-textarea#431412 – andi