使用 django-crispy-forms 覆盖默认类属性

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

我目前正在学习如何使用 django crispy forms 并且无法弄清楚这个问题。我将它与 bootstrap5 一起使用。

我有以下表格:

class CommentForm(forms.ModelForm):
    class Meta : 
        model = Comments
        fields = ["comment_content"]
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_show_labels = False
        self.fields['comment_content'].widget.attrs['placeholder'] = 'comment here...'
        self.helper.layout = Layout(
            "comment_content",
        )
        self.helper.layout.append(Submit("post_comment", "Post comment",css_class="btn btn-outline-primary"))

问题出在最后一行:而不是用 css_class 的值替换默认类(btn btn-primary),它只是在之后添加这个值,所以生成的 html 如下:

<input type="submit" name="post_comment" value="Post comment" class="btn btn-primary btn-outline-primary" id="submit-id-post_comment">

如何使结果类是“btn btn-outline-primary”而不是“btn btn-primary btn-outline-primary”?

python django django-forms django-crispy-forms
2个回答
1
投票

在用

crispy-form
(完全提交元素)分析
bootstrap5
布局的源代码后,似乎默认的css类是
btn btn-primary
(来自源代码):

class Submit(BaseInput):  
    # ...
    input_type = "submit"
    field_classes = "btn btn-primary"

所以你可以修改你的代码如下:

    # ...
    self.helper.layout = Layout(
            "comment_content",
    )
    _submit = Submit("post_comment", "Post comment")
    _submit.field_classes = 'btn btn-outlined-primary '
    self.helper.layout.append(_submit)

1
投票

阅读提交类文档(https://django-crispy-forms.readthedocs.io/en/latest/api_layout.html#layout.Submit),我们看到:

css_classstr,可选

附加的 CSS 类应用于 .默认无

这意味着提供给 css_class 的字符串不会覆盖默认值,它只会添加到默认值。

要找到默认值,我们需要查看提交类的源代码(https://django-crispy-forms.readthedocs.io/en/latest/_modules/layout.html)我们看到以下内容:

class Submit(BaseInput):
    input_type = "submit"
    field_classes = "btn btn-primary"

然后我们可以通过替换相同的代码结构来创建自定义按钮:

class CustomSubmit(BaseInput):
    input_type = "submit"
    field_classes = "btn btn-outline-primary"

然后我能够修复有问题的行:

self.helper.layout.append(CustomSubmit("post_comment", "Post comment",))

生成的 html 现在对应于 bootstrap 概述类:

<input type="submit" name="post_comment" value="Outlined comment button" class="btn btn-outline-primary" id="submit-id-post_comment">

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