如何在Django的ImageField中重命名、清除和更改标签

11

我对django相对较为陌生。我正在使用ImageForm从用户获取图像路径。

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

它展示了如下的图像小部件:

enter image description here

我想重新命名标签- 当前,清除和更改。 [基本上我的整个页面都不是小写字母,所以我想把这些标签文本也变成像当前,清除和更改那样的小写字母]。

有没有办法做到这一点?

2个回答

10

你有很多选择。

你可以使用 CSS 艺术地将文本转换为小写字母。

或者,你可以在 Python/Django 中更改发送到浏览器的文本。

最终,表单字段小部件通过一个名为 render() 的函数控制 html 输出到视图。"ClearableFileInput" 小部件的渲染() 函数使用来自小部件类的一些变量。

你可以创建自己的自定义类,将 ClearableFileInput 类作为子类,并替换自己的小写文本字符串。例如:

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)

2

如果您想要比子类化ClearableFileInput,创建widgets.py文件等更简单的方法,则可以参考以下步骤。

如果您已经在forms.py文件中子类化了ModelForm,只需修改该表单的__init__()即可。

例如:

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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接