2016-12-16 43 views
1

我在我的Django應用程序如下觀點:樣式化generic.edit.CreateView形式在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的根據視圖中指示的字段組成和輸出表格。但是,似乎沒有機會使用CSS來設置表單字段的樣式。我怎樣才能做到這一點?

回答

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 
+0

是否然後可能樣式Django的形式創建? – MadPhysicist

+1

@MadPhysicist - 查看鏈接的問題 – Sayse