Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- *views.py*
- def get_members(request):
- if 'query' in request.GET:
- q = request.GET.get('query', '').capitalize()
- member_list = []
- member_dict = {}
- members = Member.objects.all().filter(
- Q(last_name__icontains=q) |
- Q(first_name__icontains=q) |
- Q(number__icontains=q)
- ).distinct()
- for m in members:
- member_list.append(m.search_result)
- member_dict['options'] = member_list
- data = json.dumps(member_dict)
- mimetype = 'application/json'
- return HttpResponse(data, mimetype)
- return HttpResponse()
- *models.py*
- @property
- def search_result(self):
- "Returns the member's number: full name in autocomplete search."
- return '%s: ' '%s %s' % (self.number,self.first_name,self.last_name)
- *html template*
- {% csrf_token %}
- <input type="search" name="searched_item" id="searched_item" class="form-
- control" autocomplete="off" placeholder="Enter member name to be searched
- (eg. John Smith)" style="max-width: 700px;width: 700px;color:
- threeddarkshadow;">
- <script>
- $(document).ready(function($) {
- $('#searched_item').typeahead({
- items:12,
- source: function (query, process) {
- return $.get('/membership/search/', { query: query }, function (data) {
- return process(data.options);
- });
- },
- minLength:1,
- autoSelect:false,
- highlighter: function (item) {
- var regex = new RegExp( '(' + this.query + ')', 'gi' );
- return item.replace( regex, "<strong style='color:#7dcc79;' >$1</strong>" );
- },
- });
- })
- </script>
- *urls.py*
- path('search/',views.search_members,name='autocomplete member names')
Add Comment
Please, Sign In to add comment