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 ?
Setting a placeholder attribute on a HTML element is straightforward, but in Django you normally let a Form class deal with rendering your HTML form. Therefore, in order to set a placeholder value for a form field in Django you should pass the placeholder as an attribute to a form widget.
To set placeholder text in a field in your form, you only need to add a placeholder option and a text value to the form-tag representing the field. You can use the placeholder option in the following types of form tags: text, email, url, tel, textarea, number, range, date, and captchar.
Placeholders are an easy way to define sections in an HTML template that will be filled with content from the database when the page is rendered. This content is edited using django CMS's frontend editing mechanism, using Django template tags. fullwidth. html contains a single placeholder, {% placeholder "content" %} .
A widget is Django's representation of an HTML input element. The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget. The HTML generated by the built-in widgets uses HTML5 syntax, targeting <! DOCTYPE html> .
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'}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With