带有引导程序的Django modelform [英] django modelform with bootstrap

查看:62
本文介绍了带有引导程序的Django modelform的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用引导程序格式化我的模型形式,而没有任何其他程序包(仅使用引导程序源文件)。我要配置的特定表单:

I want to format my modelforms with bootstrap, and without any additional packages (just using the bootstrap source files). A particular form that I want configured:

class FoodForm(forms.ModelForm):

    class Meta:
        model = Food
        fields = ['name', 'company']
        exclude = ('user', 'edit')

名称是我想作为引导文本字段的文本字段,公司是选择字段(通过外键)

The 'name' is a text field I'd want to be a bootstrap text field, and 'company' is a selection field (from a foreign key) that I'd want to be a bootstrap dropdown.

表单模板的当前设置:

    {% extends "mainsite/base.html" %}

    {% block content %}

    <form method="POST" class="post-form">{% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn btn-primary">Save</button>
</form>
    </form> 

    {% endblock %}

格式化django模型的最佳做法是什么

What's best practice for formatting any django modelform field into bootstrap?

推荐答案

引导字段的窍门是注入 form-control 类放入每个字段,并确保每个字段都位于 form-group dom元素内。将该类注入到您的每个字段中,您可以这样:

The trick to bootstrap fields is injecting the form-control class into each field, and making sure each field lives inside a form-group dom element. To inject that class into each one of your fields, you could so something like:

class FoodForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(FoodForm, self).__init__(*args, **kwargs)
        for field in iter(self.fields):
            self.fields[field].widget.attrs.update({
                'class': 'form-control'
        })

现在,在django模板中,您可以遍历表单字段,将每个字段放入一个引导的 form-group 。例如:

Now, in your django template you can iterate through your forms fields, placing each one into a bootstrap'd form-group. For example:

<form method="POST" class="post-form">
    {% for field in form %}
    <div class="form-group">
        {{ field }}
    </div>
    {% endfor %}
</form>

我还要说,这种设置(Django + Bootstrap)在当今非常普遍,所以谷歌搜索用django引导程序形式应该在进一步定制它方面产生大量的知识。祝你好运!

I'll also say that this setup (Django + Bootstrap) is super common now adays, so googling "Bootstrap forms with django" should yield a wealth of knowledge on customizing this even further. Good luck!

这篇关于带有引导程序的Django modelform的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆