django添加占位符文本以形成字段 [英] django add placeholder text to form field

查看:560
本文介绍了django添加占位符文本以形成字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中,我有以下代码在HTML页面上创建用户名和密码表单:

 < div类=控制组> 
{{form.username}}
< / div>
< div class =control-group>
{{form.password}}
< / div>

我想在字段中添加用户名和密码占位符文本,然后当用户点击字段消失。什么是最好的方式来实现这一目标?

占位符属性


$ b

  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 '] ='用户名'
self.fields ['password'] .widget.attrs ['placeholder'] ='密码'

  class LoginForm(forms.Form):
username = forms .CharField(label ='username',widget = forms.TextInput(attrs = {'placeholder':'username'}))
password = forms.CharField(label ='password',widget = forms.PasswordInput (attrs = {'placeholder':'password'}))


In Django I have the below code which is creating a username and password form on an HTML Page:

<div class="control-group">
    {{ form.username }}
</div>
<div class="control-group">
    {{ form.password }}
</div>

I want to add "Username" and "Password" placeholder text within the field, and then when the user clicks on the field the word dissapears. What is the best way to achieve this ?

解决方案

You must use the placeholder properties

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'

or

class LoginForm(forms.Form):
    username = forms.CharField(label='username',widget=forms.TextInput(attrs={'placeholder':'username'}))
    password = forms.CharField(label='password',widget=forms.PasswordInput(attrs={'placeholder':'password'}))

这篇关于django添加占位符文本以形成字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆