Beispiel #1
0
    def get(self, request):
        cart = request.session.get('cart')
        categories = Category.getAllCategory()
        products = Product.getAllProduct().order_by('-id')

        if request.GET.get('id'):
            filterProductById = Product.objects.get(
                id=int(request.GET.get('id')))
            return render(request, 'productDetail.html', {
                "product": filterProductById,
                "categories": categories
            })

        if not cart:
            request.session['cart'] = {}

        if request.GET.get('category_id'):
            filterProduct = Product.getProductByFilter(
                request.GET['category_id'])
            return render(request, 'home.html', {
                "products": filterProduct,
                "categories": categories
            })

        return render(request, 'home.html', {
            "products": products,
            "categories": categories
        })
Beispiel #2
0
def show_category(request, category_key, 
                  template_name="store_category.html"):
    key = db.Key(category_key)
    query = Category.gql('WHERE __key__ = :1 AND is_active = True', key)
    category = query.get()
    if not category:
        raise Http404('Category not found!')
    products = category.products
    page_title = category.name
    return render_to_response(template_name, locals(), context_instance=RequestContext(request))
Beispiel #3
0
def show_category(request, category_key, template_name="store_category.html"):
    key = db.Key(category_key)
    query = Category.gql('WHERE __key__ = :1 AND is_active = True', key)
    category = query.get()
    if not category:
        raise Http404('Category not found!')
    products = category.products
    page_title = category.name
    return render_to_response(template_name,
                              locals(),
                              context_instance=RequestContext(request))
def populate():
    xl_book = xlrd.open_workbook('data.xlsx', 'rb')
    xl_sheet = xl_book.sheet_by_index(1)
    main_category = Category(id=1, name='main', parent_category=None, image_link='-', level=0)
    main_category.save()
    for cat_row in xrange(5, xl_sheet.nrows):
        cat_id = int(xl_sheet.cell(cat_row, 0).value)
        cat_title = xl_sheet.cell(cat_row, 1).value
        cat_parent_id = xl_sheet.cell(cat_row, 2).value
        print(cat_title)

        try:
            cat_image_link = xl_sheet.cell(cat_row, 3).value
        except IndexError:
            cat_image_link = 'http://www.clipartbest.com/cliparts/dc7/5dR/dc75dRdc9.jpeg'

        if cat_parent_id:
            parent_category = Category.objects.get(pk=cat_parent_id)
        else:
            parent_category = main_category

        cat_level = parent_category.level + 1

        category = Category(id=cat_id,
                            name=cat_title,
                            parent_category=parent_category,
                            image_link=cat_image_link,
                            level=cat_level)
        category.save()
 def init_category(self):
     ''' Method that retrieve data from API and fill table Category. '''
     api = OpenFoodFactsApi()
     category_list = []
     # Retrieve categories from API
     for json_category in api.fetch_categories_data_api()[:2000]:
         try:
             category = Category.from_api(json_category)
             category.save()
             category_list.append(category.name)
         except IntegrityError as error:
             logger.warn(error)
     return category_list
    def handle(self, *args, **options):
        if Category.objects.exists() or Category.objects.exists():
            print('Product already loaded...existing.')
            print(ALREADY_LOADED_ERROR_MESSAGE)
            return

        print('Creating category data')
        for name in CATEGORY_IMAGE_NAMES.keys():
            category = Category(categoryName=name)
            category.categoryImgPath = CATEGORY_IMAGE_NAMES[name]
            category.save()

        print('Loading product data from csv file')
        for line in DictReader(open('./product_data.csv')):
            product = Product()
            product.productName = line['productName']
            product.productPrice = line['productPrice']
            product.productDescription = line['productDescription']
            product.productImgPath = line['productImgPath']
            product.category = Category.objects.get(
                categoryName=line['productCategory'])
            product.save()
Beispiel #7
0
 def test_get_category_page(self):
     category = Category.all().get()
     url = category.get_absolute_url()
     response = self.client.get(url)
     self.assertEqual(response.status_code, httplib.OK)
     
 #def NO_test_get_product_page(self):
 #    product = Product.all().get()
 #    url = product.get_absolute_url()
 #    response = self.client.get(url)
 #    self.assertEqual(response.status_code, httplib.OK)
     
     
def main1(request):

    books = None
    categories = Category.get_all_categories()
    categoryID = request.GET.get('category')
    if categoryID:
        books = book.get_all_books_by_categoriesid(categoryID)
    else:
        books = book.get_all_books()
    data = {}
    data['books'] = books
    data['categories'] = categories

    return render(request, 'main1.html', data)
Beispiel #9
0
    def test_fetch_products_data_api(self, mock_get):
        ''' Test the recovery of products data from api. '''
        category = Category()
        category.name = 'Category test name'
        category.save()

        mock_response = mock.Mock()
        # Mock products data in api
        expected_api_products = {
            'products': [{
                'product_name': 'aliment',
                'ingredients_test_fr': 'ingredient',
                'url': "https://url_prod",
                'image_url': 'https://image_url_product',
            }]
        }
        mock_response.json.return_value = expected_api_products
        mock_get.return_value = mock_response
        response = OpenFoodFactsApi().fetch_products_data_api(category)
        self.assertEqual(response, expected_api_products['products'])
        # Making sure the right url was called
        mock_get.assert_called_once_with(
            f'''https://fr.openfoodfacts.org/categorie/{category}.json''')
Beispiel #10
0
    def get(self, request):
        context = {}
        categories = Category.get_all_categories()
        category_id = request.GET.get('category')       
        if category_id:
            products = Product.get_products_by_category_id(category_id)
        else:
            products = Product.get_all_products()
        context['products'] = products
        context['categories'] = categories

        cart = request.session.get('cart')
        if not cart:
            cart = {}
        request.session['cart'] = cart
        return render(request, 'index.html', context)
Beispiel #11
0
    def get(self, request):
        cart = request.session.get('cart')
        if not cart:
            request.session['cart'] = {}
        products= None
        category = Category.get_all_category()
        categoryID = request.GET.get('category')
        if categoryID:

            products = Product.get_all_product_by_category_id(categoryID)
        else:
            products = Product.get_all_products()
        
        data = {}
        data['product']=products
        data['category']=category
        return render(request,'store/index.html',data)
Beispiel #12
0
def add_category(request):
    if request.method == 'POST':
        form = categoryForm(request.POST or None)
        category = Category()
        if form.is_valid():
            category.name = form.cleaned_data.get('name')
            category.author = request.user
            category.save()
            return redirect('Product_category')
    form = categoryForm()
    context = {'form': form}
    return render(request, 'staff/add-category.html', context)
Beispiel #13
0
    def get(self, request):

        cart = request.session.get('cart')
        if not cart:
            request.session.cart = {}
        products = Product.get_all_products()
        categories = Category.get_all_categories()

        # Delivering filtered products by category
        categoryID = request.GET.get('category')
        if categoryID:
            products = Product.get_all_products_by_category_id(categoryID)
        else:
            products = Product.get_all_products()

        data = {'products': products, 'categories': categories}
        print("User = ", request.session.get('customer_email'))
        # return render(request, 'orders/orders.html')

        return render(request, 'index.html', data)
Beispiel #14
0
    def get(self, request):
        if request.user.is_anonymous is not True:
            print(request.user.is_seller)
            print(request.user)
            if request.user.is_seller:
                seller = Seller.objects.get(seller=request.user)
                request.session["customer"] = seller.id
            elif request.user.is_customer:
                customer = Customer.objects.get(customer=request.user)
                request.session["customer"] = customer.id

        cart = request.session.get('cart')
        categories = Category.getAllCategory()
        products = Product.getAllProduct().order_by('-id')

        if request.GET.get('id'):

            filterProductById = Product.objects.get(
                id=int(request.GET.get('id')))
            return render(request, 'productDetail.html', {
                "product": filterProductById,
                "categories": categories
            })

        if not cart:
            request.session['cart'] = {}

        if request.GET.get('category_id'):
            filterProduct = Product.getProductByFilter(
                request.GET['category_id'])
            return render(request, 'home.html', {
                "products": filterProduct,
                "categories": categories
            })

        return render(request, 'home.html', {
            "products": products,
            "categories": categories
        })
Beispiel #15
0
    def get(self, request):

        cart = request.session.get('cart')
        if not cart:
            request.session['cart'] = {}
        products = None
        categories = Category.get_all_categories()
        categoryID = request.GET.get('category')
        if categoryID:
            products = Product.get_all_products_by_CategoryId(categoryID)
        else:
            products = Product.get_all_products()
        data = {}
        data['products'] = products
        data['categories'] = categories

        # print(products)
        # return render(request,'orders/order.html')
        # return HttpResponse('<H1>Index Page</H1>')

        print("hello", request.session.get('email'))
        return render(request, 'index.html', data)
Beispiel #16
0
 def test_get_category_page(self):
     category = Category.all().get()
     url = category.get_absolute_url()
     response = self.client.get(url)
     self.assertEqual(response.status_code, httplib.OK)
Beispiel #17
0
 def get_object(self, queryset=None):
     self.kwargs[self.pk_url_kwarg] = Category.get_root_category_id()
     return super().get_object(queryset)
Beispiel #18
0
def buildtree(request):
    Category.build_tree()
    return render(request, 'default/x_buildtree.html', {
    })
 def create_category(self, id, parent, name):
     self.stdout.write('Creating category: id=%s, parent_id=%s, name=%s' %
                       (id, parent, name))
     parent_id = None if parent == "0" else int(parent)
     category = Category(id=int(id), parent_id=parent_id, name=name)
     category.save()
Beispiel #20
0
def save_category(category):
    data = category.cleaned_data
    name = data['name']
    category_to_save = Category(name=name)
    category_to_save.save()
Beispiel #21
0
def add(request):
    if request.session.has_key('seller'):
        id = request.session['seller']
        if request.method == 'POST':

            MyLoginForm = ProductEntryForm(request.POST)
            print(MyLoginForm.errors)
            if MyLoginForm.is_valid():
                name = MyLoginForm.cleaned_data['name']
                company = MyLoginForm.cleaned_data['company']
                price = MyLoginForm.cleaned_data['price']
                availability = MyLoginForm.cleaned_data['availability']
                cat = MyLoginForm.cleaned_data['category']
                other = MyLoginForm.cleaned_data['other']

                dbuser = Sellers.objects.filter(id=id)
                if cat == "Other":
                    categ = Category()
                    categ.name = other
                    categ.save()

                if not cat == "Other":
                    category = Category.objects.filter(name=cat)
                else:
                    category = Category.objects.filter(name=other)

                if Products.objects.filter(name=name,
                                           company=company,
                                           seller=dbuser):
                    x = Products.objects.filter(name=name, company=company)[0]

                if Products.objects.filter(name=name,
                                           company=company,
                                           category=category,
                                           seller=dbuser[0]):
                    x = Products.objects.filter(name=name,
                                                company=company,
                                                category=category)[0]

                    x.price = price
                    x.availability = availability
                    x.save(update_fields=['price', 'availability'])
                else:
                    product = Products()
                    product.productID = "GBDP{0}{1}".format(
                        id, Products.objects.count())
                    product.name = name
                    product.company = company
                    product.price = price
                    product.availability = availability
                    product.category = category[0]
                    product.seller = dbuser[0]
                    product.save()

                categories = Category.objects.all()
                products = Products.objects.filter(seller=dbuser[0])
                context = {
                    'dbuser': dbuser,
                    'products': products,
                    'categories': categories,
                }
                return render(request, 'seller/dashboard.html', context)

        else:
            dbuser = Sellers.objects.filter(id=id)
            mysearch = ProductSearchForm(request.GET)
            if mysearch.is_valid():
                search = mysearch.cleaned_data['searchfield']

                productlist = list(
                    Products.objects.filter(name__icontains=search, seller=id))

                productlist = list(
                    Products.objects.filter(name__icontains=search, seller=id))
                productlist.extend(
                    list(
                        Products.objects.filter(company__icontains=search,
                                                seller=id)))
                categories = Category.objects.all()

                context = {
                    'dbuser': dbuser,
                    'products': productlist,
                    'categories': categories,
                }
                return render(request, 'seller/dashboard.html', context)
            else:
                products = Products.objects.filter(seller=dbuser[0])
                categories = Category.objects.all()
                context = {
                    'dbuser': dbuser,
                    'products': products,
                    'categories': categories,
                }
                return render(request, 'seller/dashboard.html', context)

    else:
        return render(request, 'seller/index.html')
from store.models import Category, Product
import random
import string

pics = ['cpu_amd.jpeg', 'cpu_intel.jpeg', 'GPU.jpeg', 'gpu_amd.jpg', 'gpu_nvidia.jpeg', 'index.jpeg', 'keyboard.jpg', 'keyboard_hp.jpg', 'keyboard_razor.png']

IsInShoppingCart = [True, False]
iteration = 0

for i in range(10000):
	for j in pics:
		a = Category()
		a.name = ''.join(random.choice(string.ascii_uppercase) for _ in range(6))
		a.category_logo = random.choice(pics)
		a.save()

		for k in range(10):
			b = Product()
			b.maker = ''.join(random.choice(string.ascii_uppercase) for _ in range(6))
			b.model = ''.join(random.choice(string.digits) for _ in range(6))
			b.description = 'descr' + str(i) + ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(25))
			b.price = ''.join(random.choice(string.digits) for _ in range(3))
			b.category = a
			b.product_logo = random.choice(pics)
			b.is_in_shopCart = random.choice(IsInShoppingCart)
			b.save()
			iteration += 1
			print "iteration: {}".format(iteration)