Reputation: 5831
I have the following view in my Django app:
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)
This view corresponds to the following template:
{% 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 %}
Obviously, Django composes and outputs the form based on the fields indicated in the View. However, it seems to leave no chance to style the form fields with CSS. How can I do that?
Upvotes: 1
Views: 1582
Reputation: 43300
You'll need to provide the get_form_class
function of the view and set that to a modelform_factory with a baseclass that provides bootstrap styling - See Applying bootstrap styles to django forms for a simple example of this.
class TodoCreateView(generic.edit.CreateView):
def get_form_class(self):
return modelform_factory(self.model, form=MyBaseForm, fields=self.fields)
Otherwise, its much easier to create a form yourself and then set that to form_class
class TodoForm(MyBaseForm):
pass
form_class = TodoForm
Upvotes: 1