Python 如何使用django crispy表单制作引导文件浏览按钮

Python 如何使用django crispy表单制作引导文件浏览按钮,python,html,django,twitter-bootstrap-3,django-crispy-forms,Python,Html,Django,Twitter Bootstrap 3,Django Crispy Forms,这是我的Djangoforms.py脚本,使用 我可以创建以下表单: 如图所示,我想让浏览按钮具有引导风格。 如何才能做到这一点 我在想这样的事情: Django呈现的完整HTML如下所示: django crispy的原料*/ asteriskField先生{ 显示:无; } .表格管制{ 字号:18px; 字体系列:“Helvetica Neue”,HelveticaNeue; } .形成水平{ 左侧填充:120px; 右边填充:130px; 字体大小:20px; 字体系列:“Helv

这是我的Djangoforms.py脚本,使用

我可以创建以下表单:

如图所示,我想让浏览按钮具有引导风格。 如何才能做到这一点

我在想这样的事情:

Django呈现的完整HTML如下所示:

django crispy的原料*/ asteriskField先生{ 显示:无; } .表格管制{ 字号:18px; 字体系列:“Helvetica Neue”,HelveticaNeue; } .形成水平{ 左侧填充:120px; 右边填充:130px; 字体大小:20px; 字体系列:“Helvetica Neue”,HelveticaNeue; }

输入文件*
物种*
老鼠
人类
正常化*
基因计数
总分
对数刻度

我知道这是一篇老文章,但对于任何感兴趣的人来说,Crispy Forms在文档中都有以下内容:

 FieldWithButtons: You can create an input connected with buttons:

 FieldWithButtons('field_name', StrictButton("Go!"))


这在脆表单的文档中

对于那些发现这一点的人,前面的答案不起作用。OP要求的是文件输入字段,而不是任何类型的带有按钮的字段。Crispy似乎从未打算解决这个问题(请参阅)。使用
FieldWithButtons
将创建一个具有相同默认按钮的输入字段,以及一个显示“Go”的脆按钮,如下所示:

要做到这一点,唯一简单的方法是创建一个浏览按钮模板,在创建字段时只需调用
template=.html
。我从BaseInput模板中提取了一些代码来实现这一点,并且它可以正常工作

文件_input.html

<label for="{% if input.id %}{{ input.id }}{% else %}{{ input.input_type }}-id-{{ input.name|slugify }}{% endif %}" class="btn btn-secondary">
    {% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
    Browse
    <input type="file"
           name="{% if input.name|wordcount > 1 %}{{ input.name|slugify }}{% else %}{{ input.name }}{% endif %}"
           class="{{ input.field_classes }}"
           id="{% if input.id %}{{ input.id }}{% else %}{{ input.input_type }}-id-{{ input.name|slugify }}{% endif %}"
           hidden
           >
</label>
views.py

def profile(request):
    p_form = ProfileUpdateForm(request.POST, instance=request.user.profile, files=request.FILES)
    #...etc...

结果:

有用的链接,但将其嵌入到脆表单中会更容易。。。
class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['image']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
            # Fieldset('', *self.fields),
            Fieldset('', Button('image', "Browse", css_class="clearablefileinput form-control-file", template="file_input.html", css_id="id_image")),
            FormActions(
                Submit('save', 'Update Profile'),
            )
        )
def profile(request):
    p_form = ProfileUpdateForm(request.POST, instance=request.user.profile, files=request.FILES)
    #...etc...