I need to wrap the fields in div. In Django 1.10:
class CustomSelectDateWidget (SelectDateWidget):
def render(self, name, value, attrs=None):
...
output = []
for field in self._parse_date_fmt():
if field == 'year':
output.append('<div class="input-field col s4">' + html['year'] + '</div>')
elif field == 'month':
output.append('<div class="input-field col s5">' + html['month'] + '</div>')
elif field == 'day':
output.append('<div class="input-field col s3">' + html['day'] + '</div>')
return mark_safe('\n'.join(output))
It dosn`t work in Django 1.11. I tried to override 'django/forms/widgets/select_date.html':
class CustomDateWidget(SelectDateWidget):
def get_template_names(self):
return ['accounts/custom_select_date.html']
But Django include 'django/forms/widgets/select_date.html' instead of my template 'accounts/templates/accounts/custom_select_date.html'. No error messages are displayed.
So I found a simple way to do it. In my case I wanted to show the image in an ImageField. Here's teh codez:
Copy django's clearable_file_input.html
template, customise it and save it to, e.g. django_overrides/forms/widgets/clearable_file_input.html
, e.g.:
{% if is_initial %}{{ initial_text }}: <img src="{{ widget.value.url }}" />{% if not widget.required %}
<input type="checkbox" name="{{ checkbox_name }}" id="{{ checkbox_id }}" />
<label for="{{ checkbox_id }}">{{ clear_checkbox_label }}</label>{% endif %}<br />
{{ input_text }}:{% endif %}
<input type="{{ widget.type }}" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %} />
Subclass the original widget, setting the template_name
to your new template:
from django.forms import ClearableFileInput
class CustomClearableFileInputWidget(ClearableFileInput):
template_name = 'django_overrides/forms/widgets/clearable_file_input.html'
Update your forms to use this widget:
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
exclude = ['id', 'user']
widgets = {
'photo': CustomClearableFileInputWidget,
}