【问题标题】:form field inline with label using django-crispy-forms使用 django-crispy-forms 与标签内联的表单字段
【发布时间】:2021-05-29 22:25:59
【问题描述】:

我正在使用crispy 来呈现我的表单,但在呈现单个字段内联而不影响其他字段时遇到问题。

这个表格:

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/ 标签与输入字段位于同一行。我该怎么做?

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

【问题讨论】:

    标签: django django-crispy-forms


    【解决方案1】:

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

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

    让我知道它是否有效

    【讨论】:

    • 不幸的是,这并没有改变
    【解决方案2】:

    我自己通过 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 的标签。但现在看起来不错:

    【讨论】:

      猜你喜欢
      • 2013-10-06
      • 2015-02-02
      • 2012-11-09
      • 2014-12-07
      • 2019-12-31
      • 2015-01-07
      • 2014-02-22
      • 1970-01-01
      • 2015-05-13
      相关资源
      最近更新 更多