Skip to content

Instantly share code, notes, and snippets.

@icarovirtual
Last active April 21, 2020 22:25
Show Gist options
  • Save icarovirtual/67f8766bce5a8207b48379d67e576e75 to your computer and use it in GitHub Desktop.
Save icarovirtual/67f8766bce5a8207b48379d67e576e75 to your computer and use it in GitHub Desktop.
class BaseFilterForm(forms.Form):
def __init__(self, *args, **kwargs):
# Receive the filter instances from the view
filters = kwargs.pop('filters', [])
super(BaseFilterForm, self).__init__(*args, **kwargs)
for f in filters:
# Create dynamic form fields from the filter
self.fields[f.parameter_name] = \
forms.ChoiceField(label=f.title, choices=[('', "Select")] + f._lookups(), required=False)
# Use in your view
class ArticleView(BaseFilterView, FormView):
template_name = 'articles.html'
# Use the form
form_class = BaseFilterForm
def get_context_data(self, **kwargs):
context_data = super().get_context_data(**kwargs)
articles = Article.objects.all()
# Call the filter function wherever you want to use it
context_data['articles'] = self.apply_filters(articles)
return context_data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment