首页 > 解决方案 > 如何在django表单的输入框中设置值示例

问题描述

我想做完全相同的事情,唯一的区别是用户输入文本时默认文本消失

name = models.CharField(max_length=16, default="default value")

例子:

在此处输入图像描述

在此处输入图像描述

我正在为我的表单使用这种方法

class Device(models.Model):
    phone_regex = RegexValidator(regex=r'^[0-9]{10}$', message="Error: Format 0611223344")

    name = models.CharField(max_length=16, default="default value")
    [....cut code....]

class DeviceForm(ModelForm):
    class Meta:
        model = Device
        fields = ['name']

标签: pythoncssdjangodjango-modelsdjango-forms

解决方案


看起来您想要在您的字段上使用占位符值。将以下代码添加到您的 Form 类。

name = forms.CharField(
    label='Name', 
    widget=forms.TextInput(attrs={'placeholder': 'Type name here...'})
)

推荐阅读