使用 django-crispy-forms 与标签内联表单字段

问题描述 投票:0回答:3

我使用脆皮来渲染我的表单,但在渲染单个字段内联而不影响其他字段时遇到问题。

此表格:

class SettingsUpdateForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('about_text', 'github_name')
        labels = {
            'about_text': '',
            'github_name': 'github.com/'  # TODO make inline with field
        }
        widgets = {
            'about_text': forms.Textarea(attrs={'placeholder': 'Describe yourself!💯'}),
            'github_name': forms.TextInput(attrs={'placeholder': 'your_github_name'})
        }
        help_texts = {
            'github_name': 'Showcase a project instead: <em>/username/fav_project</em>',
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper(self)  # this is required to display the help_texts

呈现如下:

我希望

github/
标签与输入字段位于同一行。我该怎么做?

水平表格将使所有标签成为引导网格模型的一部分 - 这是我不想要的。
我也尝试使用Inline Forms,但也不起作用。

django django-crispy-forms
3个回答
1
投票

我自己通过 hack 解决了这个问题。这是我想出的解决方案:

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.helper = FormHelper(self)
    '''
    hacky solution - replace the standard label with a fake label. 
    Wrap those 2 as columns of a Row - use col-auto on first to not have whitespace between.
    Use g-0 to not have gutters between columns - padding and margin would else create whitespace
    '''
    self.helper.layout = Layout(
        Div('about_text'),
        Row(
            # create a "fake" label with a HTML Column
            Column(HTML('<em class="fab fa-github fa-2x"></em> github.com/'), css_class='col-auto'),
            Column('github_name', css_class='col'),
            css_class='row g-0'
        )
    )

我还必须删除

github_name
的标签。但现在看起来不错:


0
投票

在您的小部件中,您需要包含让 Crispyforms 知道如何渲染它的属性。 试试这个:

'github_name': forms.TextInput(attrs={'class': 'form-control', 
                                      'placeholder': 'your_github_name'})

如果有效请告诉我


0
投票

我找到了另一个解决方案。这并不完全是作者想要实现的目标,但在许多情况下很有用。我在输入字段中使用了 PrependText 属性。

self.helper.form_show_labels = False
self.helper.layout = Layout(
    Div(
        Div(PrependedText('date_from', "from:"), css_class='col-md-5'),
        Div(PrependedText('date_to', "to:"), css_class='col-md-5'),
        Div(Submit('submit', 'Filter'), css_class='col-md-2'),
        css_class='row',
        )
)

表格如下所示:

这适用于脆皮引导5

© www.soinside.com 2019 - 2024. All rights reserved.