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

11 投票
2 回答
4019 浏览
提问于 2025-04-18 15:26

我对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)

它显示的图片控件如下:

在这里输入图片描述

我想改一下标签的名字——现在是“Clear”和“Change”。(其实我整个页面的文字都是小写的,所以我也想把这两个标签的文字改成小写,比如“clear”和“change”)。

有没有什么办法可以做到这一点呢?

2 个回答

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"
10

你有很多选择。

你可以用CSS来把文字变成小写,这样看起来更有艺术感。

或者你也可以在Python/Django中直接修改发送给浏览器的文本。

最终,表单字段的控件决定了通过一个叫render()的函数输出到视图的HTML内容。对于“ClearableFileInput”控件,render()函数会使用一些来自控件类的变量。

你可以自己创建一个新的类,继承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)

撰写回答