【问题标题】:How to use html form 'placeholder' property with standard view?如何在标准视图中使用 html 表单“占位符”属性?
【发布时间】:2019-02-13 17:58:17
【问题描述】:

我是 Django 新手,正在使用 Django 的用户身份验证包 (django.contrib.auth) 进行用户登录、密码重置等。

现在,虽然一切正常,但在登录表单上,我想使用 html-placeholder 属性。我该如何使用/填充它?我确实找到了一些答案(例如this one),但我不明白该代码的放置位置、如何扩展视图/表单甚至模型(例如添加新字段),因为这是随标准包一起提供的。

现在,我添加了以下内容: 表格.py 从 django 导入表格 从 django.contrib.auth.forms 导入 AuthenticationForm

class LoginForm(forms.Form):
  username = forms.CharField(label='username')
  password = forms.CharField(label='password')

  def __init__(self, *args, **kwargs):
      super(LoginForm, self).__init__(*args, **kwargs)
      self.fields['username'].widget.attrs['placeholder'] = 'Username'
      self.fields['password '].widget.attrs['placeholder'] = 'Password'

我不确定我需要在 urls.py 或 models.py 或其他任何地方做什么才能执行代码。

【问题讨论】:

  • 可能有不同的方法。如果您向我们展示您的表单和 html,将会有所帮助。
  • 嗯,这就是我的意思...我不知道该怎么做。当我查看提供的链接时,我不太确定如何添加/扩展它。

标签: python django placeholder


【解决方案1】:

我找到了以下解决方案:

  • 已安装 bootstrap4
  • 在我的 html 中使用以下标签:

{% bootstrap_field form.password field_class="field" placeholder="Password" show_label=False %}

【讨论】:

    【解决方案2】:

    我相信通过将小部件添加到表单 init 中,当您在模板中实例化表单时,占位符应该看起来像预期的那样。您是否只是尝试在模板中呈现您的表单,例如 {{form}} 并查看它是否呈现它?我不认为 bootstrap4 是必要的,但它是一个很棒的工具。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      • 2014-06-20
      • 2018-11-01
      • 2018-10-10
      • 2018-02-19
      • 1970-01-01
      • 2018-10-25
      相关资源
      最近更新 更多