Django:ModelForm中的内联表单字段

时间:2014-09-16 05:33:33

标签: django

如何将字段放在一行中,就像我对ModelAdmin一样。

在ModelAdmin类中,我们使用模型类属性初始化fields变量,如:

@admin.register(Profile)
class AdminProfile(admin.ModelAdmin):
    fields = ['team', ('first_name', 'last_name'), 'designation', ...]

但是,如果我使用ModelForm的Meta类fields变量,那么这会引发异常,例如:

class PostsModelForm(forms.ModelForm):
    ...
    class Meta:
        model = Profile
        fields = ['team', ('first_name', 'last_name'), 'designation', ...]

RAISED ERROR: TypeError: Error when calling the metaclass bases sequence item 0: expected string or Unicode, tuple found

2 个答案:

答案 0 :(得分:0)

ModelForms不提供渲染表单的任何奇特方式。只有3 defaults methods,它们不灵活。换句话说,ModelForms主要用于从模型实例构造表单对象,添加一些验证规则等。

您需要的是django-cripsy-forms

或者你可以render your form fields manually

答案 1 :(得分:0)

我自己解决了这个问题。

这是解决方案......

创建ModelForm子类

class ProfileModelForm(forms.ModelForm):
    x_field = forms.CharField(required=True)
    ...
    class Meta:
        model = Profile
        fields = []
        # Initialize `fields` variable with empty list

    def save(self, *args, **kwargs):
        # @TODO: Extra cooking on model instance (self.instance)
        # and self properties like `x_field`
        return super(PostsModelForm, self).save(*args, **kwargs)

为Admin注册Model类并创建ModelAdmin子类:

@admin.register(Profile)
class AdminProfile(admin.ModelAdmin):
    # Assign `ProfileModelForm` to form variable
    form = ProfileModelForm
    ...
    # Here initialize the `fields` variable for `Profile` model fields
    # and `ProfileModelForm` property
    fields = ['team', ('first_name', 'last_name'), 'designation', 'x_field', ...]