How to rename currently, Clear and Change labels in ImageField of Django
Asked Answered
D

2

11

I am relatively new to django. I am using ImageForm to get the image path from the user.

class EditProfileForm(ModelForm):
    username = CharField(label='User Name', widget=TextInput(attrs={'class': 'form-control'}), required=True)
    image = ImageField(label='Select Profile Image',required = False)

It is showing the image widget as follows:

enter image description here

I want to rename the labels - Currently, Clear and Change. [Basically my entire page is no lower case, so I wanted to make these label text also in lower case like currently, clear & change].

Is there any way to do this?

Dao answered 31/7, 2014 at 3:26 Comment(0)
M
10

You have many options.

You could be artistic with the use of CSS to make the text lowercase.

or you can change the text that is sent to the browser in python/django.

Ultimately the form fields widget is what controls the html output to the view via a function called render(). The render() function for the "ClearableFileInput" widget uses some variables from the widgets class.

You can make your own custom class subclassing the ClearableFileInput class and substitute your own lowercase text strings. ie:

from django.forms.widgets import ClearableFileInput

class MyClearableFileInput(ClearableFileInput):
    initial_text = 'currently'
    input_text = 'change'
    clear_checkbox_label = 'clear'

class EditProfileForm(ModelForm):
    image = ImageField(label='Select Profile Image',required = False, widget=MyClearableFileInput)
Militant answered 31/7, 2014 at 6:49 Comment(0)
S
3

Dusting off this old question, if you want something simpler than subclassing ClearableFileInput, creating a widgets.py file, etc.

If you already subclass ModelForm in a forms.py file, just modify the __init__() of that form.

For example:

class EditProfileForm(ModelForm):
    username = CharField(label='User Name', widget=TextInput(attrs={'class': 'form-control'}), required=True)
    image = ImageField(label='Select Profile Image',required = False)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['image'].widget.clear_checkbox_label = 'clear'
        self.fields['image'].widget.initial_text = "currently"
        self.fields['image'].widget.input_text = "change"
Steradian answered 3/3, 2021 at 2:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.