N
N
nurzhannogerbek2017-08-24 13:13:43
Django
nurzhannogerbek, 2017-08-24 13:13:43

How to change html template for ImageField in edit form?

Hello! Please help me figure it out.
I have an edit form with an ImageField field . By default, Django renders the following template (see below). How to change the template correctly? I have tried the following code but template_with_initial is not working. Although initial_text , input_text and clear_checkbox_label work. I could be wrong, but I think template_with_initial only works with FileField.
widgets.py:

from django.forms.widgets import ClearableFileInput

class CustomClearableFileInput(ClearableFileInput):
    initial_text = 'Текущее изображение'

    input_text = 'Изменить'

    clear_checkbox_label = 'Очистить'

    template_with_initial = (
        '<span>%(initial_text)s</span>:'
        '<a href="%(initial_url)s">%(initial)s</a>'
        '%(clear_template)s<br/><span>%(input_text)s</span>: %(input)s'
    )

    template_with_clear = '%(clear)s'
    '<label for="%(clear_checkbox_id)s">%(clear_checkbox_label)s</label>'

forms.py:
class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        exclude = ('id',)
        widgets = {
            'image': CustomClearableFileInput
        }

What Django outputs in the template:
Текущее изображение:
<a href="/media/images/2017/08/23/picture.jpg">images/2017/08/23/picture.jpg</a>
Изменить:
<input name="image" id="id_image" type="file">

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nurzhannogerbek, 2017-08-31
@nurzhannogerbek

The problem was solved in the following way. After these settings, Django saw a template file.

INSTALLED_APPS = [
    'django.forms',
]

FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question