Note: This question shouldn't be conflated with past questions that are similar but before Django 1.11, when they released template-based form rendering.
I understand that Django now has template-based form rendering. From what I understand, this is supposed to fix the issue of having to inject CSS classes from the view or the form, rather than keeping all of the HTML/CSS in the templates.
That is my goal: to keep my forms and views focused on what is displayed, and my templates focused on how that is displayed. So I want to keep all HTML/CSS in my templates.
So, my questions are:
- How do I add a class (for example,
form-text
) to allTextInput
widgets from the template system? - How do I add a class (for example,
alert-warning
) to all error messages (validation failures) from the template system?
I may have misunderstood something about this new feature, so if I did, feel free to let me know if this isn't how it works or if I am asking the impossible. Ideally, I would like to implement these form rendering changes to the master template.
Sample Problem
views.py
:
class SignUp(generic.edit.CreateView):
model = models.User
template_name = 'usermgmt/sign_up.html'
form_class = forms.UserCreateForm
success_url = '/sign_up_done/'
templates/master.html
(I want to put something in here that causes all TextInput
widgets to get a class):
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<title>{% block title %}{% endblock %} | Website</title>
</head>
<body>
<div class="content-wrapper clearfix">
{% block main %}{% endblock %}
</div>
</body>
</html>
templates/usermgmt/sign_up.html
:
{% extends 'master.html' %}
{% block title %}Sign Up{% endblock %}
{% block main %}
<h1>Sign Up</h1>
<p>Enter your email to sign up!</p>
<form class="form-group" method="post">
{% csrf_token %}
<input type="hidden" name="next" value="{{ next }}">
{{ form.as_p }}
<button class="btn btn-primary" type="submit">Sign Up</button>
</form>
{% endblock %}