steven2308
steven2308

Reputation: 2521

forms.hiddenInput not working

I have this form to add a new Instance

class NuevoFormulario(ModelForm):
    class Meta:
        model = Usuario
        widgets = {
            'email': forms.TextInput(attrs={'required':'required'}),
            'account': forms.HiddenInput(),
            'type': forms.HiddenInput(),
        }

In my template I have this table..

<table class="table-bordered table-hover">
<tbody>
    {% for field in form %}
        <tr class="control-group {% if field.errors %} alert alert-error error {% endif %}  ">
            <td>
                {{ field.label }}
            </td>
            <td>
                {{ field }}
            </td>
            <td>
                {{ field.errors }}
            </td>
        </tr>
    {% endfor %}
</tbody>

The account must not be shown in the template as I will assing it in the views to same of the current user, this should be enough, ( and it works if I used the form as_p option, but I want it inside a nice table and have some more control so I'm showing field by field.

the PROBLEM is that the hiddenInput attribute is only working for the input, not the label, so I see all the form I want with an aditional label 'account' with no input next to it (The same happens with 'type' )

I also tried putting this in the widgets:

'account': forms.TextInput(attrs={'type':'hidden'}),

But same result. The other thing I tried to do was checking in the template if the field type was hidden, something like this:

{{ field.widget.attrs.type }}

But it shows nothing, the only attribute I could access to, was max_length.

Any solution or other idea? Thanks for the time!

Upvotes: 0

Views: 1884

Answers (2)

drabo2005
drabo2005

Reputation: 1096

With the forms.HiddenInput() it's going to be hard to get something show up! I suggest you to use django password forms:

'account': forms.RegexField(label ="Password",regex=r'^(?=.*\W+).*$',help_text='',
                    widget=forms.PasswordInput,min_length=6,)

Upvotes: -1

Samuele Mattiuzzo
Samuele Mattiuzzo

Reputation: 11048

You want to change your for loop like this

{% for field in form.visible_fields %}

to iterate only over the visible fields. See this link for reference.

Also, to check if the field is hidden, you must use is_hidden:

{% if field.is_hidden %}
   {# Do something special #}
{% endif %}

You confused a hidden field (actually available in your templates but not visible) with a model field not being sent at all (achievable using the exclude parameter in your form's metaclass). Iterating over the fields of a form will show all (visible and hidden) except those in the exclude list.

Upvotes: 2

Related Questions