Last active
December 9, 2017 13:35
-
-
Save Tushant/bf646a8f4fdc54ef3bfa9b0d025e349c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
{% load static %} | |
<html> | |
<head> | |
<title>4niture {% block title %} HomePage {% endblock title %}</title> | |
{% include "includes/css.html" %} | |
<link rel="stylesheet" href="{%static "css/main.css"%}"> | |
</head> | |
<body> | |
{% block navbar %} | |
{% include "includes/navbar.html" %} | |
{% endblock navbar %} | |
{% block content %} | |
{% endblock content %} | |
</body> | |
{% block js %} | |
{% include "includes/js.html" %} | |
{% endblock js %} | |
</html> | |
js.html | |
{% load static %} | |
{% block js %} | |
<script src="{% static 'js/jquery.min.js' %}"></script> | |
<script src="{% static 'js/bootstrap.min.js' %}"></script> | |
<script src="{% static 'js/jquery.autocomplete.js' %}"></script> | |
<script src="{% static 'js/our_search_code.js' %}"></script> | |
{% endblock js %} | |
navbar.html | |
<div class="collapse clearfix" id="search"> | |
{% include 'search/search.html' %} | |
</div> | |
search.html | |
<form action="/find" method="get" class="navbar-form" role="search"> | |
<div class="input-group"> | |
<input type="text" name="q" id="q" autocomplete="off" class="form-control search" placeholder="what are you looking for ?"> | |
<span class="input-group-btn"> | |
<button type="submit" class="btn btn-primary"><i class="fa fa-search"></i></button> | |
</span> | |
</div> | |
<div id="selction-ajax"></div> | |
</form> | |
our_search_code.js | |
$(document).ready(function(){ | |
'use strict'; | |
$('#q').autocomplete({ | |
serviceUrl: "/search/autocomplete/", | |
minChars: 2, | |
dataType: 'json', | |
type: 'GET', | |
onSelect: function (suggestion) { | |
console.log( suggestion.value + ', data :' + suggestion.data); | |
} | |
}); | |
}); | |
function getParameterByName(name, url) { | |
if (!url) { | |
url = window.location.href; | |
} | |
name = name.replace(/[\[\]]/g, "\\$&"); | |
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), | |
results = regex.exec(url); | |
if (!results) return null; | |
if (!results[2]) return ''; | |
return decodeURIComponent(results[2].replace(/\+/g, " ")); | |
} | |
function onFacetChangeApplied(){ | |
var url = window.location.href.split("?")[0]; | |
var search_query = getParameterByName('q'); | |
var url_with_search_query = url + '?q=' + search_query | |
$('input:checkbox.facet').each(function () { | |
var sThisVal = (this.checked ? $(this).val() : null); | |
var sThisName = (this.checked ? $(this).attr('name') : null); | |
if(sThisVal !== null){ | |
url_with_search_query += '&'+encodeURIComponent(sThisName)+'='+encodeURIComponent(sThisVal); | |
} | |
}); | |
location.href = url_with_search_query; | |
return true; | |
} | |
function getQueryParams(){ | |
var vars = {}, hash; | |
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); | |
for(var i = 0; i < hashes.length; i++) | |
{ | |
hash = hashes[i].split('='); | |
vars[hash[1]] = hash[0] ; | |
} | |
return vars; | |
} | |
$( document ).ready(function() { | |
var all_params = getQueryParams(); | |
console.log(); | |
$.each( all_params, function( key, value ) { | |
id = decodeURIComponent(key).replace(/\s/g,''); | |
$('#'+id).attr('checked', 'checked'); | |
}); | |
}); | |
This file contains hidden or 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 FacetedProductSearchForm(FacetedSearchForm): | |
def __init__(self, *args, **kwargs): | |
data = dict(kwargs.get("data", [])) | |
self.categories = data.get('category', []) | |
super(FacetedProductSearchForm, self).__init__(*args, **kwargs) | |
def search(self): | |
sqs = super(FacetedProductSearchForm, self).search() | |
if self.categories: | |
query = None | |
for category in self.categories: | |
if query: | |
query += u' OR ' | |
else: | |
query = u'' | |
query += u'"%s"' % sqs.query.clean(category) | |
sqs = sqs.narrow(u'category_exact:%s' % query) | |
return sqs |
This file contains hidden or 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 Category(MPTTModel): | |
name = models.CharField(max_length=100, blank=True, null=True) | |
image = models.ImageField(null=True, blank=True, | |
upload_to=upload_furniture_image_path) | |
slug = models.SlugField(max_length=200, unique=True) | |
parent = TreeForeignKey('self', null=True, blank=True, | |
related_name='children', db_index=True) | |
class Furniture(models.Model): | |
name = models.CharField(max_length=100, blank=True, null=True) | |
slug = models.SlugField(max_length=200, unique=True) | |
price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) | |
quantity = models.PositiveIntegerField(default="0", help_text='Stock quantity') | |
content = MarkdownxField() | |
note = models.CharField(max_length=500, null=True, blank=True, help_text="Notice on the product") | |
meta_info = models.TextField(blank=True, null=True, help_text="Tips or some information related to the product") | |
category = models.ForeignKey(Category, null=True, blank=True) |
This file contains hidden or 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 haystack import indexes | |
from furnitures.models import Furniture | |
class FurnitureIndex(indexes.SearchIndex, indexes.Indexable): | |
text = indexes.CharField(document=True, use_template=True, template_name="search/indexes/furniture/furniture_text.txt") | |
name = indexes.CharField(model_attr='name') | |
category = indexes.CharField(model_attr='category', faceted=True) | |
content_auto = indexes.EdgeNgramField(model_attr='name') | |
suggestions = indexes.FacetCharField() | |
def get_model(self): | |
return Furniture | |
def index_queryset(self, using=None): | |
return self.get_model().objects.all() | |
# for f in Furniture.objects.all(): | |
#print(f.category.get_ancestors(include_self=True)) |
This file contains hidden or 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
{% extends "base.html" %} | |
{% block title %} | |
"{{ query }}" | {{ block.super }} | |
{% endblock %} | |
{% block content %} | |
<div class="container"> | |
<div class="row"> | |
{% if page_obj.object_list %} | |
<div class="col-md-3"> | |
<h3>Filters</h3> | |
<dl> | |
{% if facets.fields.category %} | |
<dt>Filter by Category</dt> | |
{% for category in facets.fields.category %} | |
{% if category.1 != 0 %} | |
<dd> | |
<input class="facet" id="{{category.0|cut:" "}}" type="checkbox" name="category" value="{{ category.0 }}" | |
data-toggle="toggle" /> {{ category.0 }} ({{ category.1 }}) | |
</dd> | |
{% endif %} | |
{% endfor %} | |
{% endif %} | |
</dl> | |
<div> | |
<input class="btn btn-info btn-sm pull-right" type="submit" value="apply filter" onclick="return onFacetChangeApplied();" /> | |
</div> | |
<dl> | |
<div class="col-md-9"> | |
<div class="row"> | |
<div class="col-md-6 col-xs-6"> | |
Search result for: <label> {{query}} </label> | |
</div> | |
<div class="col-md-6 col-xs-6 align-right"> | |
Showing {{ page_obj.start_index }} - {{ page_obj.end_index }} of total | |
{{ page_obj.paginator.count }} | |
results on page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }} | |
</div> | |
</div> | |
<div> | |
{% if page_obj.object_list %} | |
<ol class="row top20"> | |
{% for result in page_obj.object_list %} | |
<div class="showcase col-sm-6 col-md-4"> | |
<a href="{{ result.object.get_absolute_url }}"> | |
<h3>{{result.object.name}}</h3> | |
{% if result.object.first_image %} | |
<img src="{{ result.object.first_image.url }}" class="img-responsive"> | |
{% endif %} | |
</a> | |
</div> | |
{% endfor %} | |
</ol> | |
</div> | |
{% if is_paginated %} | |
<ul class="pagination pull-right"> | |
{% if page_obj.has_previous %} | |
<li><a href="?q={{ query }}&page={{ page_obj.previous_page_number }}">«</a></li> | |
{% else %} | |
<li class="disabled"><span>«</span></li> | |
{% endif %} | |
{% for i in paginator.page_range %} | |
{% if page_obj.number == i %} | |
<li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> | |
{% else %} | |
<li><a href="?q={{ query }}&page={{ i }}">{{ i }}</a></li> | |
{% endif %} | |
{% endfor %} | |
{% if page_obj.has_next %} | |
<li><a href="?q={{ query }}&page={{ page_obj.next_page_number }}">»</a></li> | |
{% else %} | |
<li class="disabled"><span>»</span></li> | |
{% endif %} | |
</ul> | |
{% endif %} | |
{% else %} | |
<p> Sorry, no result found for the search term <strong>{{query}} </strong></p> | |
{% endif %} | |
</div> | |
</div> | |
</div> | |
{% endblock %} |
This file contains hidden or 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
import json | |
from django.shortcuts import render, get_object_or_404 | |
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger | |
from django.template import RequestContext | |
from django.http import JsonResponse | |
from django.forms.models import model_to_dict | |
from django.template.loader import render_to_string | |
from haystack.query import SearchQuerySet | |
from haystack.generic_views import FacetedSearchView as BaseFacetedSearchView | |
from rest_framework import generics | |
from rest_framework import permissions | |
from .models import Furniture, Category | |
from carts.models import Cart | |
from .serializers import CategorySerializer, FurnitureSerializer | |
from .forms import FacetedProductSearchForm | |
def show_pagination(request, obj, num_of_page_to_show): | |
paginator = Paginator(obj, num_of_page_to_show) | |
page = request.GET.get('page') | |
try: | |
object_list = paginator.page(page) | |
except PageNotAnInteger: | |
object_list = paginator.page(1) | |
except EmptyPage: | |
object_list = paginator.page(paginator.num_pages) | |
return object_list | |
def furnitures(request): | |
furniture_list = Furniture.objects.all() | |
categories = Category.objects.all() | |
furnitures = show_pagination(request, furniture_list, 15) | |
cart_obj, new_obj = Cart.objects.new_or_get(request) | |
context = { | |
'furnitures': furnitures, | |
'categories': categories, | |
'cart': cart_obj | |
} | |
return render(request, 'furnitures/furnitures.html', context) | |
def furniture(request, slug): | |
instance = get_object_or_404(Furniture, slug = slug) | |
cart_obj, new_obj = Cart.objects.new_or_get(request) | |
nodes = Category.objects.all() | |
# nodes = Category.objects.add_related_count(Category.objects.all(), Furniture, 'category', 'o_count', True) | |
context = { | |
'furniture': instance, | |
'cart': cart_obj, | |
'nodes': nodes | |
} | |
return render(request, 'furnitures/furniture.html', context) | |
def show_product_on_category(request, hierarchy): | |
category_slugs = hierarchy.split('/') | |
categories = Category.objects.all() | |
furnitures = None | |
try: | |
category = Category.objects.get(slug=category_slugs[-1]).get_descendants(include_self=True) | |
furnitures = Furniture.objects.filter(category__in=category) | |
except Category.DoesNotExist: | |
print ('should show error in best possible way') | |
except Furniture.DoesNotExist: | |
furnitures = "No Furniture Exist In This Category" | |
context = { | |
'furnitures': furnitures, | |
'categories': categories | |
} | |
return render(request, 'furnitures/furnitures.html', context) | |
def autocomplete(request): | |
sqs = SearchQuerySet().autocomplete( | |
content_auto=request.GET.get( | |
'query', | |
''))[ | |
:5] | |
s = [] | |
for result in sqs: | |
d = {"value": result.title, "data": result.object.slug} | |
s.append(d) | |
output = {'suggestions': s} | |
return JsonResponse(output) | |
class FacetedSearchView(BaseFacetedSearchView): | |
form_class = FacetedProductSearchForm | |
facet_fields = ['category', ] | |
template_name = 'search/search_result.html' | |
paginate_by = 3 | |
context_object_name = 'object_list' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment