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

ppcbkaq5  于 12个月前  发布在  Go
关注(0)|答案(3)|浏览(143)

我使用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/标签与输入字段在同一行。我该怎么做呢?
水平形式将使所有标签的一部分,引导网格模型-我不希望。
我也试过使用内联表单,但也不起作用。

x4shl7ld

x4shl7ld1#

我自己破解的。这是我提出的解决方案:

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

inn6fuwd

inn6fuwd2#

我找到了另一个解决办法。这并不是作者想要实现的,但在许多情况下可能是有用的。我对输入字段使用了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',
        )
)

表单看起来像这样:

这适用于crispy-bootstrap 5

avwztpqn

avwztpqn3#

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

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

如果成功了就告诉我

相关问题