python - 使用 Bootstrap 在 Django 中设置 generic.edit.CreateView 表单的样式

标签 python css django twitter-bootstrap

我的 Django 应用程序中有以下 View :

class TodoCreateView(generic.edit.CreateView):
    model = Todo
    fields = ['todo_name','todo_description']
    template_name = 'list/todo-create.html'
    success_url = reverse_lazy('list:index')
    def form_valid(self, form):
        form.instance.owner = self.request.user
        form.instance.created_date = datetime.now()
        return super(EntryCreateView, self).form_valid(form)

此 View 对应于以下模板:

{% extends 'list/base.html' %}

{# Load the tag library #}
{% load bootstrap3 %}

{# Load CSS and JavaScript #}
{% bootstrap_css %}


{# Display django.contrib.messages as Bootstrap alerts #}
{% bootstrap_messages %}

{% block content %}

<h1>Todo:</h1>
<div>
<form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save" />
</form>

{% endblock %}

很明显,Django 根据 View 中指示的字段组合并输出表单。但是,似乎没有机会使用 CSS 来设置表单字段的样式。我怎样才能做到这一点?

最佳答案

您需要提供 View 的 get_form_class 函数并将其设置为具有提供 Bootstrap 样式的基类的 modelform_factory - 请参阅 Applying bootstrap styles to django forms举个简单的例子。

class TodoCreateView(generic.edit.CreateView):
     def get_form_class(self):
          return modelform_factory(self.model, form=MyBaseForm, fields=self.fields)

否则,自己创建一个表单然后将其设置为form_class

会容易得多
class TodoForm(MyBaseForm):
    pass

form_class = TodoForm

关于python - 使用 Bootstrap 在 Django 中设置 generic.edit.CreateView 表单的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41182820/

相关文章:

html - 为什么当浏览器窗口重新调整大小时 div 宽度没有改变?

html - 背景大小 :cover equivalent

python - 在夹层中对页面进行分组

django - 如何处理Django中不共享同一个域的前端

python - pip install --user -e/home/me/package/权限被拒绝

python - Python环境变量不起作用

python - 将二维数组中的所有非最小值设置为 NaN

python - 如何在 3-D 等高线图中绘制回归预测数据?

javascript - 搜索 div 并设置属性的 jQuery 代码

javascript - 在 django formset 中动态添加行