Created
October 2, 2012 19:03
-
-
Save fabiocerqueira/3822541 to your computer and use it in GitHub Desktop.
SearchView
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
from django.views.generic import ListView | |
from django.views.generic.edit import FormMixin | |
from django.db.models import Q | |
class SearchView(FormMixin, ListView): | |
template_name_suffix = '_search' | |
filter_operator = 'contains' | |
allow_or_operator = False | |
def get_filter_operator(self): | |
if self.filter_operator: | |
return '__' + self.filter_operator | |
else: | |
return '' | |
def get_allow_or_operator(self): | |
return self.allow_or_operator | |
def get_queryset(self): | |
queryset = super(SearchView, self).get_queryset() | |
params = dict([ | |
('%s%s' % (k, self.get_filter_operator()), v) | |
for k,v in self.request.GET.dict().iteritems() | |
if v | |
]) | |
if self.get_allow_or_operator(): | |
filter_or = Q() | |
for p in params.items(): | |
filter_or = filter_or | Q(**dict([p])) | |
queryset = queryset.filter(filter_or) | |
else: | |
queryset = queryset.filter(**params) | |
return queryset | |
def get_initial(self): | |
initial = self.initial.copy() | |
initial.update(self.request.GET.dict()) | |
return initial | |
def get(self, request, *args, **kwargs): | |
self.object_list = self.get_queryset() | |
context = self.get_context_data( | |
object_list=self.object_list, | |
form=self.get_form(self.get_form_class()) | |
) | |
return self.render_to_response(context) |
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
from django import forms | |
class SearchUserForm(forms.Form): | |
username = forms.CharField(label='Username', max_length=30) | |
first_name = forms.CharField(label='First Name', max_length=30) |
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
from django.contrib.auth.models import User | |
from baseviews import SearchView | |
from forms import SearchUserForm | |
class SearchUserView(SearchView): | |
model = User | |
form_class = SearchUserForm | |
allow_or_operator = True | |
filter_operator = 'startswith' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment