Sunday, April 7, 2013

ADDING AUTOCOMPLETE, AUTOFOCUS, PLACEHOLDER AND OTHER ATTRIBUTES TO DJANGO FORMS

In HTML its easy to give just an attribute to a tag to set autofocus or autocomplete on/off. In Django forms the way around is a little different from the traditional way.
In HTML you can set a placeholder like
<input name = "name" placeholder = "Awais Ali" type = "text" />
So in Django you can do this by
self.fields['Name'].widget.attrs['autofocus']  = 'on'
You can also assign auto-complete in a similar fashion
self.fields['Name'].widget.attrs['autofocus']  = 'off'
Similarly place-holder can be set like this
self.fields['Name'].widget.attrs['placeholder']  = u'Your Name'
This can also be set using  dictionary by giving key, value like this
self.fields['Name'].widget.attrs({'placeholder':'Your Name'}) 

So over-all if you want every field to have some property or value then here is the code how to do it


 def __init__(self, *args, **kwargs):
        super(LoginForm,self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs['autocomplete'] = 'off'
        self.fields['username'].widget.attrs['autofocus'] = 'on'
        self.fields['password'].widget.attrs['autocomplete'] = 'off'
 
    username = forms.CharField(label=_("Username"), max_length=30, widget=forms.TextInput())
    password = forms.CharField(label=_("Password"), widget=forms.PasswordInput(render_value=False))


So after putting this code in your forms.py you would achieve the required functionality. Similarly you can go on adding HTML attributes form here whatever you like to add for example:
read-only, disabled, multiple etc.

Feel free to ask if you have any queries in the comment below.


4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. I get an error that my form does not have the attribute 'fields'

    ReplyDelete
    Replies
    1. NVM. I just had to put it below my super...... Because I have other things happening in my init.
      THANKS A BUNCH

      Delete
  3. Side question. In the same form (now able to autofocus on the first field) [using CreateView and Modelform], I have an initial value set for the second input (in the CreateView `initial = {'inc_number': "INC"}`). After the user fills out the first input, I want them to be able to tab, and go to the end of the initial value (aka "INC"). But the current functionality is highlighting "INC", which then obvsiously would be typed over when they start typing. I want the "INC" to stay there.

    ReplyDelete