我的Django应用程序中有以下视图:
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)
此视图对应于以下模板:
{% 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设置表单字段的样式。我怎样才能做到这一点?
答案 0 :(得分:1)
您需要提供视图的get_form_class
功能,并将其设置为带有提供引导样式的基类的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