Pass Data from View to Form

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.

0 Comments, 0 trackbacks (Trackback URL)

0 responses to Pass Data from View to Form

Leave a Comment
  1. (required)
  2. Ignore this field:
  3. Don't put anything in this field:
    Don't put anything here:
  4. Leave this empty:
    (required)
  5. Your email is not publically displayed.