May 18th, 2009 posted by Bender Rodríguez
Pass data from your view to your form in Django.
In Django, if you want to pass data from your view to your form, say to populate a choice field with objects from one of your models, you can grab the data by whatever means you see fit and then pass it as an argument to your form class when you instantiate it. Like so:
class ContactForm(forms.Form):
def __init__( self, user_choices_list, *args, **kwargs ):
super( ContactForm, self ).__init__( *args, **kwargs )
self.fields['email'].choices = user_choices_list
email = forms.ChoiceField()
In your view, you have:
def contact(request):
variable_from_views=get_list_from_ldap(user_input_variable)
form = ContactForm(variable_from_views)
return render_to_response('contact_form.html', {'form': form})
If you're using choices you should use a ChoiceField as it will validate that the selections is one of the desired choices, which won't be validated with a CharField. However, if you don't want Django to automatically validate it is a valid choice you can just do it is a CharField and do it yourself.
See also this discussion from the Django Users group over at google.
"Death must be so beautiful. To lie in the soft brown earth, with the grasses waving above one's head, and listen to silence. To have no yesterday, and no tomorrow. To forget time, to forgive life, to be at peace."
Oscar Wilde