This has been driving me nuts and I can't get it to work. It's a simple scenario: I want to present the user with a dynamically generated list of users that I pull from the database so the user can select one of the users from a ChoiceField (rendered as an HTML select) and click a "Get Data" button.
I don't want to create a list of the users in the form because new users will come along all the time. I want to query for the users in my view and bind that list of users to the form so I can always render the latest list of users. So here's my form:
class ViewUsersForm(forms.Form):
user_choice = forms.ChoiceField()
And here's my view:
from django.contrib.auth.models import User
from mystuff.forms import ViewUsersForm
def site_admin_view_user_groups_page(request):
if request.method == 'POST':
<...handling POST for this question is unimportant...>
else:
users = User.objects.all()
data = {'user_choice': users}
form = ViewUsersForm(data) # binding the list of users here
variables = RequestContext(request, {'form': form,})
return render_to_response('school/admin/view_user_groups_page.html', variables)
And finally, here's the template I'm rendering to:
<form action="/site/viewusers/" method="post">{% csrf_token %}
{{ form.user_choice }}
<button type="submit" name="getDataButton">Get Data</button>
</form>
So when the template renders the bound form (form = ViewUsersForm(data)), the ChoiceField comes up empty. How do I get the data in the ChoiceField to render in my HTML??? What really simple thing am I missing here? Or am I going about this the completely wrong way?