﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
6407	ModelChoiceField with widget=HiddenInput doesn't behave as expected	Andy McCurdy <sedrik@…>	nobody	"I'm attempting to render a ModelChoiceField as a HiddenInput widget.  I generate the form instance within a template tag, allowing template engineers to drop in the form wherever they want.  They pass in a string parameter to the tag representing a User model instance, the tag's Node resolves it, creates a new form instance, passing {{{initial=resolved_user_var}}} to the form's {{{__init__}}} method.  I'd expect the HTML that gets generated to have an {{{<input type=""hidden"" name=""user"" value=""<id of user instance>""/>}}}.  However, the value attribute of the input tag is getting set to {{{__unicode__}}} instead.

Here are the details:

I have a model with a ForeignKey to contrib.auth.models.User.  The model looks like this:

{{{
class MyModel(models.Models):
    body = models.TextField()
    user = models.ForeignKey(User)
}}}

I then have a ModelForm for MyModel, called MyForm.

{{{
class MyForm(forms.ModelForm):
    body = forms.CharField(widget=forms.Textarea) 
    user = forms.ModelChoiceField(queryset=User.objects.none(), widget=forms.HiddenInput)
    
    class Meta:
        model = MyModel
}}}


When creating the form, which I'm currently doing using a template tag, I know the exact user instance I care about, so I pass that into as the initial argument of MyForm's __init__:

{{{
    # Normally a resolved template tag instance, but this will illustrate the point
    u = User.objects.get(id=1)
    f = MyForm(initial={'user':u})
}}}

However, when rendering the widget from my form, the value attribute of the <input> tag seems to be the result of {{{__unicode__}}} rather than the ID of the user I supplied:

{{{
    f = MyForm(initial={'user':u})
    f.as_p()

>>> u'<p><label for=""id_body"">Body:</label> <textarea id=""id_body"" rows=""10"" cols=""40"" name=""body""></textarea><input type=""hidden"" name=""user"" value=""andy"" id=""id_user"" /></p>'
}}}


I also tried supplying the ID to user_id, rather than the model instance, which outputted no value attribute at all:

{{{

    f = MyForm(initial={'user_id':u.id})
    f.as_p()

>>> u'<p><label for=""id_body"">Body:</label> <textarea id=""id_body"" rows=""10"" cols=""40"" name=""body""></textarea><input type=""hidden"" name=""user"" id=""id_user"" /></p>'
}}}


The user attribute in question is not the currently logged in user, but another user, hence why I can't just use request.user and need to pass the ID through the POST.

I'm attempting to work on a patch, but wanted to ensure the behavior I'm anticipating is what is expected."		closed	Forms	dev		worksforme	ModelChoiceField HiddenInput		Unreviewed	0	0	0	0	0	0
