user1011792
user1011792

Reputation:

Django: How to access form field input_type in a template

I am rendering a form this way:

{% for field in form %}
    <div>
        {{ field.errors }}
        <input  name="{{field.name}}" type="{{field.widget.input_type}}" placeholder="{{field.name}}">
    </div>
{% endfor %}

However, {{field.widget.input_type}} returns the empty string here, though trying it from the shell it produces the input_type. So how can I access the input type of a field from the template?

I am not using {{field}} because I need to put a placeholder in each input field.

EDIT:

I just used {{field}} and a simple javascript, that place the placeholder in each input element field to be the same as the element name, though I still would like to know how to access widget.input_type from the template.

Upvotes: 1

Views: 2236

Answers (1)

Odif Yltsaeb
Odif Yltsaeb

Reputation: 5656

Could I perhaps suggest and alternate means to get same thing?

Try putting

attrs = {'placeholder':'your placeholder text here'}

into your form field widget like this:

formfield = SomeField(widget = SomeWidget(attrs = {'placeholder':'your placeholder text here'} ))

Then you can just print out

{{ field }} 

in template and be done with it.

Edit: In response to first comment.

Since i just started new project and downloaded html5 boilerplate with nice sleek loginform on top of the page i had to just do exactly what i suggested. I did it like that:

forms.py:

from django.contrib.auth.forms import AuthenticationForm

class MyAuthenticationForm(AuthenticationForm):
    def __init__(self, *args, **kwargs):
        super(MyAuthenticationForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs['placeholder'] = self.fields['username'].label
        self.fields['password'].widget.attrs['placeholder'] = self.fields['password'].label

Now perhaps your problem is that you want to also use django.contrib.auth.views.login for logging user in and that view uses django default authentication form. Not a problem!

open your urls.py and work this magic:

from yourapp.forms import MyAuthenticationForm
from django.contrib.auth.views import login

urlpatterns = patterns('',
    url(r'^login/$',
        login,
        {'template_name': 'yourapp/login.html', 'authentication_form':MyAuthenticationForm},
        name='auth_login'),
)

works like a charm

Upvotes: 2

Related Questions