无论是在你的
admin.py
中,还是在单独的
forms.py
中,你都可以添加一个
ModelForm
类,然后像通常那样在其中声明你的额外字段。我还给出了一个例子,说明你如何在
form.save()
中使用这些值。
from django import forms
from yourapp.models import YourModel
class YourModelForm(forms.ModelForm):
extra_field = forms.CharField()
def save(self, commit=True):
extra_field = self.cleaned_data.get('extra_field', None)
# ...do something with extra_field here...
return super(YourModelForm, self).save(commit=commit)
class Meta:
model = YourModel
要让额外的字段出现在管理中,只需。
Edit your admin.py and set the form property to refer to the form you created above.
Include your new fields in your fields or fieldsets declaration.
Like this:
class YourModelAdmin(admin.ModelAdmin):
form = YourModelForm
fieldsets = (
(None, {
'fields': ('name', 'description', 'extra_field',),
在Django 1.8中,你需要将fields = '__all__'添加到YourModelForm的元类中。