想要在管理员中添加表单字段以及在django

时间:2017-02-23 16:57:55

标签: python django

我想在Admin.py页面中添加3个字段。其中两个字段来自Model.py,一个字段来自form.py.但不知何故,当我将这些字段添加到admin.site.register函数时,会弹出一个错误,提示用户列表'无法识别。以下是我的代码:

Models.py

class About(models.Model):
    about_author = models.TextField()
    pic = models.FileField(upload_to = '', default = 'static/defaul.jpg')

Form.py

class PostAuthorDetails(forms.ModelForm):
    def __init__(self,*args,**kwargs):
        super(PostAuthorDetails,self).__init__(*args,**kwargs)
        self.fields['userlist'] = forms.ModelChoiceField(queryset=User.objects.all())
    class Meta:
        model = About
        fields = '__all__'

Admin.py

class PostAuthorDetailsAdmin(admin.ModelAdmin):
    form = PostAuthorDetails

    def get_fieldsets(self,*args,**kwargs):
        return((None,{'fields':('about_author','pic','userlist'),}),)

admin.site.register(About,PostAuthorDetailsAdmin)

请告知代码错误。

1 个答案:

答案 0 :(得分:0)

FormFields是类成员。在表格初始化期间,您无法声明FormFields。

class PostAuthorDetails(forms.ModelForm):
    userlist = forms.ModelChoiceField(queryset=User.objects.all())

    class Meta:
        model = About
        '__all__'

请参阅有关ModelForms的文档:https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/