Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django add placeholder text to form field

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 ?

like image 863
Jaron787 Avatar asked May 23 '17 11:05

Jaron787


People also ask

How do I add a placeholder in Django form field?

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.

How do I add a placeholder text to a form?

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.

What is placeholder in Django?

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" %} .

What is widget in Django?

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> .


1 Answers

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'}))
like image 180
aziminia Avatar answered Nov 15 '22 06:11

aziminia