首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用django-crispy-forms的标签内联表单字段

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

Stack Overflow用户
提问于 2021-02-28 07:33:49
回答 2查看 362关注 0票数 0

我正在使用crispy呈现我的表单,但是我遇到了在不影响其他字段的情况下呈现单个字段的问题。

此表单:

代码语言:javascript
复制
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会让所有标签成为bootstraps网格模型的一部分--这是我不想要的。

我也尝试过使用Inline Forms,但也不起作用。

EN

回答 2

Stack Overflow用户

发布于 2021-02-28 07:42:15

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

代码语言:javascript
复制
'github_name': forms.TextInput(attrs={'class': 'form-control', 
                                      'placeholder': 'your_github_name'})

如果有效,请让我知道

票数 0
EN

Stack Overflow用户

发布于 2021-02-28 08:46:52

我能够用一个黑客自己解决它。这是我想出的解决方案:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66404461

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档