【问题标题】:How set example of value in input box of django form如何在django表单的输入框中设置值示例
【发布时间】:2021-10-10 14:23:03
【问题描述】:

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

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

【问题讨论】:

    标签: python css django django-models django-forms


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      这样做的方法是使用 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...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-09
        • 1970-01-01
        • 2010-10-08
        相关资源
        最近更新 更多