Skip to content

Instantly share code, notes, and snippets.

@jscn
Created August 19, 2012 08:02
Show Gist options
  • Save jscn/3393513 to your computer and use it in GitHub Desktop.
Save jscn/3393513 to your computer and use it in GitHub Desktop.
Dynamic forms with class based generic views.
class SearchForm(forms.Form):
"""
Search for users.
"""
# Search fields.
first_name = forms.CharField()
last_name = forms.CharField()
email = forms.CharField()
class SearchResultsForm(forms.Form):
"""
Display a list of matching users as (in this case) radio buttons.
"""
users = forms.ChoiceField(label='Search results', choices=(),
widget=forms.RadioSelect())
def __init__(self, search_terms, *args, **kwargs):
super(SearchResultsForm, self).__init__(*args, **kwargs)
# Get the matching users and add them as choices to a radio button input.
choices = api.fetch_users(first_name=first_name, last_name=last_name,
email=email)
self.fields['users'].choices = choices
class SearchView(FormView):
template_name = 'search.html'
form_class = SearchForm
def get_success_url(self):
return reverse('search_results')
def form_valid(self, form):
# Add the inputs from the form to the session data.
self.request.session['search_terms'] = {
'first_name': form.cleaned_data.get('first_name'),
'last_name': form.cleaned_data.get('last_name'),
'email': form.cleaned_data.get('email'),
}
return HttpResponseRedirect(self.get_success_url())
class SearchResultsView(FormView):
template_name = 'search_results.html'
form_class = SearchResultsForm
def get_success_url(self):
reverse('search_complete')
def get_form(self, form_class):
search_terms = self.request.session.get('search_terms')
return form_class(search_terms=search_terms,
**self.get_form_kwargs())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment