我想在admin.py “extra_field”中添加一个自定义字段,该字段在 forms.py 中的YourModelForm类中定义 的 forms.py
***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 = movie
fields = '__all__'
admin.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from . models import movie, genre
from . import forms
class movieAdmin(admin.ModelAdmin):
form = YourModelForm
list_display=('movie_name', 'movie_rating','Date','count',)
search_fields=('movie_name',)
filter_horizontal=('movie_genres',)
list_filter=('Date',)
date_hierarchy='Date'
ordering=('-movie_name',)
fields=('movie_name','movie_rating','movie_genres', 'extra_field',)
class genreAdmin(admin.ModelAdmin):
list_display=('genre_name',)
admin.site.register(movie, movieAdmin)
admin.site.register(genre, genreAdmin)
NameError:名称'YourModelForm'未定义
答案 0 :(得分:1)
您已整体导入forms
模块,因此您需要使用该限定名称:
form = forms.YourModelForm
(注意,这是标准的Python导入语义,与Django没有任何关系。)