def load_products(): '''Import products from API and add them in the database''' nbr = 0 for category in CATS: cat = Category(name=category) cat.save() payload = { 'action': 'process', 'tagtype_0': 'categories', 'tag_contains_0': 'contains', 'tag_0': category, 'countries': 'France', 'page_size': '250', 'json': 1 } reponse = requests.get('https://fr.openfoodfacts.org/cgi/search.pl', \ params=payload) data = reponse.json() try: for product in data['products']: try: name = product['product_name_fr'] except KeyError: try: name = product['product_name'] except KeyError: pass try: nutrition_grade = product['nutrition_grade_fr'] except KeyError: try: nutrition_grade = product['nutrition_grade'] except KeyError: pass url = product['url'] image = product['image_front_url'] try: nutrition_image = product["image_nutrition_small_url"] except KeyError: pass name = name.replace("\n", " ") name = name.replace("'", "'") product = Product(name=name, category=cat, \ nutrition_grade=nutrition_grade, url=url,\ img_url=image, nut_url=nutrition_image) nbr += 1 product.save() except KeyError: pass
def category_create(request): alreadycreated = False created = False context = RequestContext(request) if request.method == 'POST': category_form = CategoryForm(data=request.POST) user = request.user if category_form.is_valid(): category_name = category_form.cleaned_data['name'] category_ex = Category.objects.filter(name=category_name) if category_ex.exists(): alreadycreated = True else: category = Category(name=category_name, user=user, pub_date=timezone.now()) category.save() created = True else: create = False alreadycreated = True else: category_form = CategoryForm() #Search bar methods if request.method == 'GET' and 'search_category_button' in request.GET: search_category = request.GET.get('search_category') category_name = request.GET.get('search_name_c') if (category_name is not None) and (search_category is not None): return search_bar(request, search_category, category_name) if request.method == 'GET' and 'search_user_button' in request.GET: user_name = request.GET.get('search_name') if user_name is not None: return user_search(request, user_name) return render_to_response('myapp/base_category_create.html', { 'alreadycreated': alreadycreated, 'created': created }, context)
def test_tree_id(self): opts = Category()._mptt_meta newtree = Category() setattr(newtree, opts.tree_id_attr, 234) newtree.save() self.assertEqual(getattr(newtree, opts.tree_id_attr), 234) newtree = Category() setattr(newtree, opts.tree_id_attr, 134) newtree.save() self.assertEqual(getattr(newtree, opts.tree_id_attr), 134) newtree = Category() setattr(newtree, opts.tree_id_attr, 135) newtree.save() self.assertEqual(getattr(newtree, opts.tree_id_attr), 135) newtree = Category() setattr(newtree, opts.tree_id_attr, 0) newtree.save() self.assertEqual(getattr(newtree, opts.tree_id_attr), 0)