0
class BusinessMemberInlineForm(ModelForm):
    helper = FormHelper()
    username = 'no user found yet'

    def __init__(self, *args, **kwargs):
        super(BusinessMemberInlineForm, self).__init__(*args, **kwargs)

        if hasattr(self.instance, 'user'):
            self.username = self.instance.user.username

        self.helper.layout = Layout(
            Div(
                Div(
                    Column(
                        HTML('<b>%s</b>' % self.username)
                    ),
                    Column(
                        'can_post'
                    ),
                    Column(
                        'is_admin'
                    ),
                    Column(
                        'DELETE'
                    ),

                    'id',
                    'businessprofile',

                    css_class="span12"
                ),
                css_class="row-fluid"
            ),
        )

    class Meta:
        model = BusinessMember
        fields = ['can_post', 'is_admin']

这会输出如下内容:

no user found yet [x] can post? [x] is admin? [ ] remove?

no user found yet [ ] can post? [ ] is admin? [ ] remove?

代替:

Admin [x] can post? [x] is admin? [ ] remove?

Test user [ ] can post? [ ] is admin? [ ] remove?

这里有一些我不明白的地方。它似乎只保存了创建的 Cripsy 布局的最后一个实例(一个空模型),因此它只打印“尚未找到用户”。

我很困惑,我补充说print self.username并且值都设置正确。

我应该如何向表单集添加动态标签?

4

1 回答 1

0

啊!

我最终不得不制作一个自定义小部件来适当地显示每个字段中的名称,这比它应该做的要困难得多!

从 django 导入表格

我的 utils/widgets.py

class DisplayTextWidget(forms.Widget):
    display_value = ""

    def __init__(self, attrs=None, display_value="Nothing here!"):
        self.display_value = display_value

        super(DisplayTextWidget, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        return self.display_value

然后在 forms.py

self.fields['user'].widget = DisplayTextWidget(display_value=self.instance.user.username)
于 2013-06-12T19:34:53.513 回答