如何在django表单的输入框中设置值示例

How set example of value in input box of django form

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

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']

执行此操作的方法是使用 Django Forms 的 widget 属性。在这里,您可以更改将在客户端呈现的 HTML。

class YourForm(ModelForm):

    class Meta:
        model = YourModel
        fields = ('your', 'fields')
        widgets = {
            'form_field': forms.TextInput(attrs={'placeholder': "Search Content..."}
        }

以上代码将为字段 form_field 呈现一个 input 标记,并添加一个 placeholder 的 HTML 属性,值为 Search Content...

您的字段似乎需要占位符值。将以下代码添加到您的表单 class.

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