Last active
April 21, 2020 22:25
-
-
Save icarovirtual/67f8766bce5a8207b48379d67e576e75 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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