def test_product_fits_multiple_true(self): """Test product model""" category = Categories( category="Exterior" ) category.save() manufacturer = Manufacturer( name="Eibach" ) manufacturer.save() product = Product( name="Test Product", description="Description", img="", category=category, ticket_price="2.50", product_price="795", product_link="https://www.github.com", part_manufacturer=manufacturer, fits_multiple=True ) product.save() self.assertEqual(product.name, 'Test Product') self.assertEqual(product.description, 'Description') self.assertEqual(product.img, '') self.assertEqual(product.category.category, 'Exterior') self.assertEqual(product.ticket_price, '2.50') self.assertEqual(product.product_price, '795') self.assertEqual(product.product_link, 'https://www.github.com') self.assertEqual(product.part_manufacturer.name, 'Eibach') self.assertTrue(product.fits_multiple)
def publish_want_service(request): user = None try: user = Account.objects.get(id=request.session['user_id']) except: user = None if not user: return HttpResponse('false') name = request.POST.get('name', '') purpose = '3' category = request.POST.get('category', '') price = request.POST.get('price', '') condition = '0' phone = request.POST.get('phone', '') qq = request.POST.get('qq', '') campus = request.POST.get('campus', '') content = request.POST.get('content', '') validate_success = validate_publish(name, purpose, category, price, condition, phone, qq, campus, content, '','want') if not validate_success: return HttpResponse('false') big_imgs = 'big/big_default_want.jpg' small_imgs = 'small/small_default_want.jpg' product = Product(name=name, purpose=purpose, category=category, price=price, condition=condition, phone=phone, qq=qq, campus=campus, content=content, big_imgs=big_imgs, small_imgs=small_imgs, owner=user) product.save() return HttpResponse('true')
def list(request): # Handle file upload if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Product( user=request.user, title=request.POST["title"], docfile=request.FILES["docfile"], active=request.POST["active"], description=request.POST["description"], quantity=request.POST["quantity"], zip_Code=request.POST["zip_Code"], address=request.POST["address"], expire_date=request.POST["expire_date"], ) newdoc.save() # Redirect to the document list after POST # return HttpResponseRedirect(reverse('products.views.list_detail')) return redirect("products.views.post_detail_list", pk=newdoc.pk) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page # documents = Document.objects.all() # Render list page with the documents and the form return render_to_response("products/list.html", {"form": form}, context_instance=RequestContext(request))
def fill_products(self, cat): for index, value in enumerate(cat): temp_var = requests.get( "https://fr.openfoodfacts.org/cgi/search.pl?action=process&tagtype_0=labels&tag_contains_0=contains&tag_0=sans%20gluten&tagtype_1=categories&tag_contains_1=contains&tag_1={}&sort_by=unique_scans_n&page_size=100&axis_x=energy&axis_y=products_n&action=display&json=1".format( value)).json() for x, i in enumerate(temp_var['products']): category_id = Category.objects.get(name=value) try: products = Product(product_name=i['product_name_fr'], nutriscore_grade=i['nutrition_grades'], store=i['stores_tags'], url_picture=i['selected_images']['front']['display']['fr'], url_picture_small=i['selected_images']['front']['small']['fr'], url_product=i['url'], description=i['generic_name_fr'], category_id=category_id.pk) if Product.objects.filter( product_name=i['product_name_fr']).exists(): continue else: products.save() except KeyError as e: print(e) if x == 200: break
def test_add_to_cart_when_product_is_already_in_the_cart(self): ''' test add to cart when the product is already in the cart ''' # create a Product item = Product(name="Product", available_stock="100", content="product content", price="30", image="img.jpg", num_of_ratings="5", average_rating="5") # save the product item.save() # post product and quantity to cart page = self.client.post("/cart/add/{0}".format(item.id), data={'quantity': '3'}, follow=True) # post same product and quantity to cart page = self.client.post("/cart/add/{0}".format(item.id), data={'quantity': '1'}, follow=True) # check the status code is 200 self.assertEqual(page.status_code, 200) # check Template Used is products.html self.assertTemplateUsed(page, "products.html")
def setUp(self): # create Users self.test_user1 = User.objects.create_user(username='******', password='******') self.test_user2 = User.objects.create_user(username='******', password='******') # data for filters self.name_length = 3 self.price_size = 50 # create Products data_dict = { 'product1': 1, 'product2': 10, 'pr': 33, 'product4': 43, 'product6': 90 } products = [ Product(name=name, price=price, create_by=self.test_user2) if index % 2 else Product(name=name, price=price, create_by=self.test_user1) for index, (name, price) in enumerate(data_dict.items()) ] Product.objects.bulk_create(products)
def setUp(self): """Method called to prepare the test fixture.""" self.options = ChromeOptions() # self.options.add_experimental_option("excludeSwitches", # ["enable-logging"]) self.options.add_argument('--headless') self.options.add_argument('--disable-gpu') self.options.add_argument('--remote-debugging-port=9222') self.options.add_argument('--window-size=1920x1080') self.browser = Chrome(chrome_options=self.options) User = get_user_model() self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.category = Category(id_category="1à", name="category_test", products=1, visible=True) self.category.save() for id_product in range(7): self.product = Product(id_product="key%s" % id_product, product_name_fr="test_%s" % id_product, nutriscore_score=0, nutriscore_grade='A', brands='brand_test') self.product.save() self.product.categories.add(self.category)
def test_checkout_custom_templates_rendered_with_successful_call(self): """Tests if correct templates are rendered upon calling checkout URL. Placeholder data is used to successfully access the checkout page. """ User.objects.create_user(username="******", password="******") self.client.login(username="******", password="******") item = Product(name="Product", product_image="testing_img.jpg", description="Product description.", price="20.00", stock_available="5", showcase_product="True") item.save() session = self.client.session session["cart"] = {1: 1} session.save() response = self.client.get("/checkout/shipping/") self.assertTemplateUsed(response, "checkout_shipping_address.html") self.assertTemplateUsed(response, "base.html") self.assertTemplateUsed(response, "layout/head.html") self.assertTemplateUsed(response, "components/navbar.html") self.assertTemplateUsed(response, "components/footer.html") self.assertTemplateUsed(response, "layout/scripts.html")
def import_data(data, user, csvfile_data): req_fields = ['title', 'description', 'price', 'rating', 'status'] python_csv_object = csv.DictReader(csvfile_data.read().splitlines()) for i, rowData in enumerate(python_csv_object): new_product = Product() row = {} for k in rowData.keys(): row[k.replace(' ', '_').lower()] = rowData[k] if i == 0: if not all(map(lambda v: v in row.keys(), req_fields)): break for field in req_fields: setattr(new_product, field, row[field]) new_product.created_by = user new_product.save() subcat_ids = data.getlist('category') if subcat_ids: for cid in subcat_ids: subcat = CatalogCategory.objects.get(id=cid) ProductCategory.objects.create(product=new_product, category=subcat)
def test_checkout_third_party_templates_rendered_with_successful_call( self): """Tests if third-party templates are rendered upon calling checkout URL. Placeholder data is used to successfully access the checkout page. """ User.objects.create_user(username="******", password="******") self.client.login(username="******", password="******") item = Product(name="Product", product_image="testing_img.jpg", description="Product description.", price="20.00", stock_available="5", showcase_product="True") item.save() session = self.client.session session["cart"] = {1: 1} session.save() response = self.client.get("/checkout/shipping/") self.assertTemplateUsed(response, "bootstrap4/uni_form.html") self.assertTemplateUsed(response, "bootstrap4/errors.html") self.assertTemplateUsed(response, "bootstrap4/field.html") self.assertTemplateUsed(response, "django/forms/widgets/text.html") self.assertTemplateUsed(response, "django/forms/widgets/input.html") self.assertTemplateUsed(response, "django/forms/widgets/attrs.html") self.assertTemplateUsed(response, "bootstrap4/layout/help_text_and_errors.html") self.assertTemplateUsed(response, "bootstrap4/layout/field_errors_block.html") self.assertTemplateUsed(response, "bootstrap4/layout/help_text.html")
def test_submission_of_shipping_information_creates_object(self): """Tests if object is correctly created upon user submission.""" User.objects.create_user(username="******", password="******") self.client.login(username="******", password="******") item = Product(name="Product", product_image="testing_img.jpg", description="Product description.", price="20.00", stock_available="5", showcase_product="True") item.save() session = self.client.session session["cart"] = {1: 1} session.save() self.client.post( "/checkout/shipping/", { "full_name": "Homer Simpson", "primary_address_line": "742", "secondary_address_line": "Evergreen Terrace", "town_or_city": "Springfield", "county": "Undetermined", "postcode": "SI54 7JU", "country": "United States", "phone_number": "76484377" }) shipping = CustomerShipping.objects.first() self.assertEqual(shipping.full_name, "Homer Simpson") self.assertEqual(shipping.primary_address_line, "742") self.assertEqual(shipping.secondary_address_line, "Evergreen Terrace") self.assertEqual(shipping.town_or_city, "Springfield") self.assertEqual(shipping.county, "Undetermined") self.assertEqual(shipping.postcode, "SI54 7JU") self.assertEqual(shipping.country, "United States") self.assertEqual(shipping.phone_number, "76484377")
def test_paypal_discount(self): """ test if paypal discount applies with preorders """ product = Product(name="product", price=20) product.save() order = PreOrder( full_name="test", email="test", phone_number="12", country="IE", postcode="test", town_or_city="test", street_address1="test", street_address2="test", county="test", ) order.save() orderlineitem = PreOrderLineItem( order=order, product=product, quantity=1, ) orderlineitem.save() total = (product.price)*orderlineitem.quantity ie_delivery_fee = total * ( settings.IRL_STANDARD_DELIVERY_PERCENTAGE/100) grand_total = float(ie_delivery_fee + total) * ( settings.PAY_PAL_DISCOUNT/100) self.assertEqual(float(order.grand_total), grand_total)
def handle(self, *args, **options): number_categories = options['c'] number_products = options['p'] api = OpenFoodFactsAPI(number_categories, number_products) # Adding categories print(f"Adding {number_categories} categories", end="") for api_category in api.categories: category = Category(name=api_category) category.save() print(".", end="") # Adding products print( f"\nAdding {number_categories * number_products} products, it can take a little while..." ) for api_product in api.get_products(): api_product['category'] = Category.objects.get( name=api_product['category']) product = Product(**api_product) # Taking care of duplicates if any (sanity check even with a set() in api.get_products()) try: product.save() except IntegrityError: # Unicity constraint continue print( f"\nSuccessfully added {len(Product.objects.all())} products and " f"{len(Category.objects.all())} categories. Differences may be duplicates." )
def save_in_db(self, product, categ): """Save product in database. Args: product (json):all the data of 1 product. categ (string): category Return: Stored if database if does not already exists """ cln_product = self.clean_data(product) if not self.check_if_exist(int(cln_product['code'])): p = Product( product_name=cln_product['product_name'], nutrition_grades=cln_product['nutrition_grades_tags'], fat=cln_product['fat'], fat_100g=cln_product['fat_100g'], saturated_fat=cln_product['saturated-fat'], saturated_fat_100g=cln_product['saturated-fat_100g'], sugars=cln_product['sugars'], sugars_100g=cln_product['sugars_100g'], salt=cln_product['salt'], salt_100g=cln_product['salt_100g'], image_url=cln_product['image_url'], url=cln_product['url'], category=categ, last_modified_t=cln_product['last_modified_t'], id_off=cln_product['code'], ) p.save()
def test_specific_product_page(self): """Test response of a product extra detail page""" category = Categories.objects.create( category="Exterior" ) vehicle = Vehicle.objects.create( make="Mercedes", model="A Class", generation="W176" ) manufacturer = Manufacturer( name="Test Manufacturer" ) manufacturer.save() prod = Product( name="Test Product", description="Description", category=category, ticket_price="2.50", product_price="795", product_link="https://www.github.com", fits=vehicle, part_manufacturer=manufacturer ) prod.save() response = self.client.get('/tickets/' + str(prod.id) +'/') self.assertEqual(response.status_code, 200)
def handle(self, *args, **kwargs): # load categories data categories = load_json_data('categories') ProductCategory.objects.all().delete() for category in categories: new_category = ProductCategory(name=category['name'], description=category['description']) new_category.save() # load products data products = load_json_data('products') Product.objects.all().delete() for p in products: # get category_id by name category_id = ProductCategory.objects.get(name=p['category']).id # add new product new_product = Product(category_id=category_id, name=p['name'], short_desc=p['short_desc'], description=p['description'], price=p['price'], quantity=p['quantity']) new_product.save() # add image to related product img = ProductImage(product_id=new_product.id, image=p['image']) img.save()
def test_render_search_page(self): self.user = User.objects.get(username="******") self.product = Product(make="test") self.product.save() url = self.client.get('/search/=test') self.assertEqual(url.status_code, 200) self.assertTemplateUsed(url, 'products.html')
def test_get_product_detail_page(self): product = Product(title="TestTitle", price="5") product.save() page = self.client.get("/products/{0}/".format(product.id)) self.assertEqual(page.status_code, 200) self.assertTemplateUsed(page, "product_detail.html")
def add_products(self): """ populating db """ url = 'https://fr-en.openfoodfacts.org/category/pizza.json' response = requests.get(url) products_data = response.json() products = products_data['products'] nutriscore = '' prod_name = '' prod_url = '' for i in range(len(products)): if not products[i]['nutriscore_grade']: print('error') if products[i]['nutriscore_grade']: nutriscore = products[i]['nutriscore_grade'] print('nutriscore: ', nutriscore) if not products[i]['url']: print('error') if products[i]['url']: prod_url = products[i]['url'] print('url: ', prod_url) prod_name = products[i]['product_name'] print('prod name: ', prod_name) data = Product(name=prod_name, url=prod_url, nutrition_grade=nutriscore, category="pizza", date=timezone.now()) data.save() return products
class ProductViewsTest(TestCase): def setUp(self): """datas call before each funtion""" #a cat self.category = Category(name="jus de fruits") self.category.save() #a product self.product1 = Product( name="Pur jus d'orange sans pulpe", image_url="https://static.openfoodfacts.org/images/products/350/211/000/9449/front_fr.80.400.jpg", url="https://world.openfoodfacts.org/product/3502110009449/pur-jus-d-orange-sans-pulpe-tropicana", nutriscore=3, packaging="carton") self.product1.save() def test_redirect_when_no_prod(self): """ tests whether access is impossible when user is authenticated""" response = self.client.get(reverse("products:infos"), follow=True) self.assertEqual(response.status_code, 200) self.assertRedirects(response, reverse('research:index')) def test_display_page_when_prod_arg(self): """ tests whether access is possible when user is authenticated""" response = self.client.get("/p10/products/infos/Pur jus d'orange sans pulpe") self.assertEqual(response.status_code, 200)
def setUp(self): # Create the model instances required for the relationship self.new_difficulty = Difficulty(name="Very Tough") self.new_difficulty.save() self.new_category = Category(name="Solid Cakes") self.new_category.save() # Create the raw data for testing raw_data = { "name": "Cherry Cake", "price": 3000, "average_class_size": 25, "difficulty_level": self.new_difficulty, "description": "Good Stuff", } product_raw_data = { "name": "Fairy Cake", "price": 3000, "category": self.new_category, "description": "Great Cake!", "sizes": "S" } #Pass the dictionary as named parameters to a function call self.new_lesson = Lesson(**raw_data) self.new_lesson.save() self.new_product = Product(**product_raw_data) self.new_product.save() self.user = User.objects.create_user(username='******', password='******') self.client.login(username='******', password='******')
def _import(cls, products): for product in products: p = Product( is_customizable=product['is_customizable'], delivery=product['delivery'], kids=product['kids'], name=product['name'], relative_url=product['relative_url'], discount_percentage=product['discount_percentage'], kid_adult=product['kid_adult'], free_porto=product['free_porto'], image=product['image'], sizes=product['sizes'], package=product['package'], price=cls._clean_float(product['price']), discount_type=product['discount_type'], product_labels=product['product_labels'], url=product['url'], online=product['online'], price_old=cls._clean_float(product['price_old']), currency=product['currency'], img_url=product['img_url'], id=product['id'], women=product['women'], ) p.save()
def test_home_view(self): """ This test makes sure the home page is rendered correctly. """ product = Product(name='vine', price=12.99) product.save() products = Product.objects.all() page = self.client.get('/', {'products': products}) self.assertEquals(page.status_code, 200)
def post(self, request): success_message = '' product_with_owner = Product() product_with_owner.owner = request.user form = ProductForm(request.POST, request.FILES, instance=product_with_owner) if form.is_valid(): form.save() success_message = '¡Producto publicado con éxito!' context = { 'form_category': form.data['category'], 'form_description': form.data['description'], 'form_functionality': form.data['functionality'], 'form_image': format_html( '<img src=/media/{}/{} width="230" height="200"/>'.format( request.user, request.FILES['image'])), 'form_location': form.data['location'], 'success_message': success_message, } return render(request, 'products/newProductOk.html', context)
def test_removing_an_item_from_the_cart(self): ''' test removing an item from the cart ''' # create a Product item = Product(name="Product", available_stock="100", content="product content", price="30", image="img.jpg", num_of_ratings="5", average_rating="5") # save the product item.save() # post product and quantity to cart page = self.client.post("/cart/add/{0}".format(item.id), data={'quantity': '3'}, follow=True) # post same product and quantity to cart page = self.client.post("/cart/adjust/{0}".format(item.id), data={'quantity': '0'}, follow=True) # check the status code is 200 self.assertEqual(page.status_code, 200) # check Template Used is products.html self.assertTemplateUsed(page, "cart.html")
def setUp(self): # Create the model instances required for the relationship self.new_difficulty = Difficulty(name="Very Tough") self.new_difficulty.save() self.new_category = Category(name="Solid Cakes") self.new_category.save() # Create the raw data for testing lesson_raw_data = { "name":"Cherry Cake", "price": 3000, "average_class_size": 25, "difficulty_level": self.new_difficulty, "description": "Good Stuff", } product_raw_data = { "name": "Fairy Cake", "price": 3000, "category":self.new_category, "description": "Great Cake!", "sizes": "S" } self.new_lesson = Lesson(**lesson_raw_data) self.new_lesson.save() self.new_product = Product(**product_raw_data) self.new_product.save()
def product_accept_add(request): if request.user.is_superuser: if request.method == 'POST': product_id = request.POST['product_id'] product_name = request.POST['product_name'] product_image = request.POST['product_image'] company = request.POST['company'] product_description = request.POST['product_description'] quantity = request.POST['quantity'] price = request.POST['price'] product = Product(product_id=product_id, product_name=product_name, product_image=product_image, company=company, product_description=product_description, quantity_in_stock=quantity, sell_price=price) product.save() return redirect('/products') messages.add_message(request, messages.INFO, 'Error! Please refill the form to add a product') return redirect('/admin/products/add') return HttpResponse("You don't have permission to view this page")
def save_product(request): if request.method == 'POST': product_specification = calculate_product_specification(request) product_list_names = calculate_product_list_names(product_specification) product = Product(product_name=product_specification['product_name'], user_id=product_specification['user_id'], is_base_product=product_specification['is_base_product'], is_optional_product=product_specification['is_optional_product'], is_custom_product=product_specification['is_custom_product'], desired_amount=product_specification['desired_amount'], current_amount=product_specification['current_amount'], lacking_amount=product_specification['lacking_amount']) products = get_products_for(request.user.id) if is_product_assigned_to_any_product_list(product_specification): product.save() messages.success(request, 'You have added new product to ' + product_list_names) else: messages.error(request, 'Please specify at least one product list') use_as_default_tab = True if not is_product_assigned_to_any_product_list(product_specification) else False context = { 'base_products': products['base_products'], 'optional_products': products['optional_products'], 'custom_products': products['custom_products'], 'base_product_active': product_specification['is_base_product'], 'optional_product_active': product_specification['is_optional_product'], 'custom_product_active': product_specification['is_custom_product'], 'use_as_default_tab': use_as_default_tab } return render(request, 'accounts/dashboard.html', context)
def list(request): document = Document.objects.filter(user_id=request.user.id)[:1] if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Product(user=request.user, title=request.POST['title'], docfile=request.FILES['docfile'], active=request.POST['active'], description=request.POST['description'], quantity=request.POST['quantity'], zip_Code=request.POST['zip_Code'], address=request.POST['address'], expire_date=request.POST['expire_date']) newdoc.save() return redirect('products.views.post_detail_list', pk=newdoc.pk) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page return render_to_response('products/list.html', { 'document': document, 'form': form }, context_instance=RequestContext(request))
def sales(request, pk): object_list = Product.my_query.active_with_qty() instance = get_object_or_404(RetailOrder, id=pk) form = SalesForm(instance=instance) search_name = request.GET.get('search_name', None) barcode = request.GET.get('barcode', None) object_list = object_list.filter( Q(title__icontains=search_name) | Q(sku__icontains=search_name) ).distinct() if search_name else object_list if barcode: RetailOrderItem.barcode(request, instance) if request.POST: form = SalesForm(request.POST, instance=instance) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('pos:sales', kwargs={'pk': pk})) form_paid = Product(request.POST) if form_paid.is_valid(): form_paid.save() return HttpResponseRedirect(reverse('pos:sales', kwargs={'pk': pk})) object_list = object_list[:10] context = locals() return render(request, 'PoS/sales.html', context)
def setUp(self): category = Category(name='maria_sharia') category.save() product = Product(name='name', description='description', offer='99.00') product.save()
def add_non_existing_item(text, amount, user): product = Product(name=text) product.save() new_kitchen = ProductInKitchen(product=product, owner=user, quantity=amount) new_kitchen.save()
def list(request): document = Document.objects.filter(user_id=request.user.id).order_by("-docfile")[:1] if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Product( user=request.user, title=request.POST["title"], docfile=request.FILES["docfile"], active=request.POST["active"], description=request.POST["description"], quantity=request.POST["quantity"], zip_Code=request.POST["zip_Code"], address=request.POST["address"], expire_date=request.POST["expire_date"], ) newdoc.save() return redirect("products.views.post_detail_list", pk=newdoc.pk) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page return render_to_response( "products/list.html", {"document": document, "form": form}, context_instance=RequestContext(request) )
def item_edit_service(request): user = None try: user = Account.objects.get(id=request.session['user_id']) except: user = None if not user: return HttpResponse('false') pid = request.POST.get('pid', '') name = request.POST.get('name', '') purpose = request.POST.get('purpose', '') category = request.POST.get('category', '') price = request.POST.get('price', 0) condition = request.POST.get('condition', '') phone = request.POST.get('phone', '') qq = request.POST.get('qq', '') campus = request.POST.get('campus', '') content = request.POST.get('content', '') files = request.FILES file_list = list(request.FILES.keys()) try: product = Product.objects.get(id=pid) if not product.owner==user: return HttpResponse('false') except: return HttpResponse('false') validate_success = validate_publish(name, purpose, category, price, condition, phone, qq, campus, content, files) if not validate_success: return HttpResponse('false') # Get big_imgs and small_imgs big_imgs, small_imgs = build_big_imgs_and_small_imgs(files) # Save imgs save_success = save_big_and_small_files(big_imgs, small_imgs, files) if not save_success: return HttpResponse('false') product = Product(id=product.id, name=name, purpose=purpose, category=category, price=price, condition=condition, phone=phone, qq=qq, campus=campus, content=content, big_imgs=big_imgs, small_imgs=small_imgs, owner=user) product.save() return HttpResponse('true')
def setUp(self): self.ipn_record = IPNRecord( transaction_id=1, data='a=1', ) self.ipn_record.save() self.order = Order( donation=100, status=Order.SHOPPING_CART, ) self.order.save() self.product = Product( name='Test Product', slug='test-product', price=500, tax_deductible=50, min_quantity=0, max_quantity=10, current_quantity=5, status=Product.FOR_SALE, ) self.product.save() self.product_in_order = ProductInOrder( order=self.order, product=self.product, quantity=1, ) self.product_in_order.save()
def list(request): if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): newdoc = Product(user = request.user, title = request.POST['title'], docfile = request.FILES['docfile'], active = request.POST['active'], description = request.POST['description'], quantity = request.POST['quantity'], zip_Code = request.POST['zip_Code'], address = request.POST['address'], expire_date = request.POST['expire_date']) newdoc.save() return HttpResponseRedirect(reverse('products:post_detail_list',args=(newdoc.pk,))) else: form = ProductForm() # A empty, unbound form # Load documents for the list page return render_to_response( 'products/list.html', { 'form': form}, context_instance=RequestContext(request) )
def handle(self, **options): product_json = get_json() for item in product_json: # Try to find product - if it doesn't exist, create a new DB entry try: product = Product.objects.get(pk=item["id"]) except Product.DoesNotExist: product = Product() for key, value in item.items(): if not key in ["sizes"]: if key in ["price", "price_old"]: product.__dict__[key] = value.replace(",", ".") elif key in ["kids", "kid_adult", "women", "free_porto"]: product.__dict__[key] = int(value) else: product.__dict__[key] = value product.from_json = True product.save() # Create a list of product sizes from the json product_sizes = item["sizes"].split(",") # Create product sizes, and add the sizes to the product for item in product_sizes: size, created = ProductSize.objects.get_or_create(title=item) product.sizes.add(size) return None
def profile(request, username): current_user_profile_url = get_current_user_profile_url(request) profile_user = User.objects.get(username=username) if not profile_user: raise Http404 can_review = request.user.can_review(profile_user) products = Product.listing().filter(user=profile_user) products_sold_count = Product.objects.filter(user=profile_user, purchase__isnull=False).count() return render_to_response("profiles/profile.html", locals(), context_instance=RequestContext(request))
def list(request): document = Document.objects.filter(user_id = request.user.id).order_by('-docfile')[:1] if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Product(user = request.user, title = request.POST['title'], docfile = request.FILES['docfile'], active = request.POST['active'], description = request.POST['description'], quantity = request.POST['quantity'], zip_Code = request.POST['zip_Code'], address = request.POST['address'], expire_date = request.POST['expire_date']) newdoc.save() return redirect('products.views.post_detail_list', pk=newdoc.pk) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page return render_to_response( 'products/list.html', {'document': document, 'form': form}, context_instance=RequestContext(request) )
def addProduct(request, template_name='products/add_product.html'): if request.method == 'POST': addform = AddProductForm(request.POST) if addform.is_valid(): data = addform.cleaned_data product = Product(name=data['name'], price=data['price'], instock=data['units'], ptype=data['ptype'], brand=data['brand']) product.save() addform = None else: addform = AddProductForm() context = {'user': request.user, 'addform': addform} return render_to_response(template_name, context, context_instance = RequestContext(request))
def update_reset_candidates(products=Product.objects.all()): """Reset update bestbuys on list set of products""" bestbuy_fields = Product.get_bestbuy_fields() updates = {} for fld in bestbuy_fields : updates['%s' %fld] = 0 #apply the updates product_update = products.update(**updates) print "PRODUCT_COUNT= %s" %product_update
def addProductPOSTHandler(post_request): product_exists = True try: brand = Brand.objects.get(name=post_request['brand']) except Brand.DoesNotExist: brand = Brand(name=post_request['brand']) brand.save() product_exists = False try: category = Category.objects.get(name=post_request['category']) except Category.DoesNotExist: category = Category(name=post_request['category']) category.save() product_exists = False try: ptype = ProductType.objects.get(name=post_request['ptype']) except ProductType.DoesNotExist: ptype = ProductType(name=post_request['ptype'], category=category) ptype.save() product_exists = False try: product = Product.objects.get(name=post_request['name']) product = [] except Product.DoesNotExist: if not product_exists: product = Product( name=post_request['name'], price=post_request['price'], instock=post_request['units'], brand=brand, ptype=ptype) product.save() return product
def list(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Product(user = request.user, title = request.POST['title'], docfile = request.FILES['docfile'], active = request.POST['active'], quantity = request.POST['quantity'], zip_Code = request.POST['zip_Code'], address = request.POST['address'], date_created = request.POST['date_created'],date_Update = request.POST['date_Update'], expire_date = request.POST['expire_date']) newdoc.save() # Redirect to the document list after POST #return HttpResponseRedirect(reverse('products.views.list_detail')) return redirect('products.views.post_detail_list', pk=newdoc.pk) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page #documents = Document.objects.all() # Render list page with the documents and the form return render_to_response( 'products/list.html', {'form': form}, context_instance=RequestContext(request) )
def index(request, product_uuid=None): product = None if not product_uuid else Product.objects.get(uuid=product_uuid) if request.method == 'POST': p = Product() p.name = request.POST.get('name', None) p.description = request.POST.get('description', None) p.image_url = request.POST.get('image_url', None) p.url = request.POST.get('url', None) p.author = request.user if request.user.id else None p.save() if not product and Product.objects.count() != 0: product = Product.objects.order_by('-created')[0] ctx = { 'product': product, 'latest': Product.objects.order_by('-created')[:5], } return render_to_response('index.html', ctx, context_instance=RequestContext(request))
def ajax_products_analysis(request): data = dict() switcher = request.GET.get('analysis') queryset = Product.my_query.active_warehouse() queryset = Product.filters_data(request, queryset) queryset_analysis = [0, 0, 0] # total_qty, #total_warehouse_value, #total_sell_value if switcher == 'warehouse_analysis': queryset_analysis[0] = queryset.aggregate(Sum('qty'))['qty__sum'] if queryset else 0 queryset_analysis[1] = queryset.aggregate(total=Sum(F('qty') * F('price_buy')))['total'] if queryset else 0 queryset_analysis[2] = queryset.aggregate(total=Sum(F('qty') * F('final_price')))['total'] if queryset else 0 data['results'] = render_to_string(request=request, template_name='report/ajax/warehouse/ajax_warehouse_analysis.html', context={'queryset_analysis': queryset_analysis, 'currency': CURRENCY, 'switcher': switcher } ) if switcher == 'vendor_analysis': vendor_analysis = queryset.values('supply__title').annotate(total_ware_price=Sum(F('qty')*F('final_price')), total_sell_price=Sum(F('qty')*F('price_buy')) ).order_by('supply__title') data['results'] = render_to_string(request=request, template_name='report/ajax/warehouse/ajax_warehouse_analysis.html', context={'vendor_analysis': vendor_analysis, 'currency': CURRENCY, 'switcher': switcher, } ) if switcher == "sells_analysis": sells_items = RetailOrderItem.objects.filter(title__in=queryset) if queryset else None sells_analysis = sells_items.values('title__title').annotate(total_sells=Sum(F('qty')), incomes=Sum(F('qty')*F('final_price')) ).order_by('-incomes')[:30] data['results'] = render_to_string(request=request, template_name='report/ajax/warehouse/ajax_warehouse_analysis.html', context={ 'sells_analysis': sells_analysis, 'currency': CURRENCY, 'switcher': switcher } ) if switcher == 'buy_analysis': pass return JsonResponse(data)
def setUp(self): """ Sets up environment for tests """ super(TestItemResource, self).setUp() self.create_user() self.client.login(username='******', password='******') #Create supplier, customer and addrss self.customer = Customer(**base_customer) self.customer.save() self.supplier = Supplier(**base_supplier) self.supplier.save() self.address = Address(address1="Jiggle", contact=self.customer) self.address.save() #Create a product to add self.product = Product.create(self.user, **base_product) self.product.save() self.fabric = Fabric.create(**base_fabric) f_data = base_fabric.copy() f_data["pattern"] = "Stripe" self.fabric2 = Fabric.create(**f_data) #Create acknowledgement ack_data = base_ack.copy() del ack_data['customer'] del ack_data['items'] del ack_data['employee'] del ack_data['project'] self.ack = Estimate(**ack_data) self.ack.customer = self.customer self.ack.employee = self.user self.ack.save() #Create an item self.item_data = {'id': 1, 'quantity': 1, 'is_custom_size': True, 'width': 1500, "fabric": {"id":1}} self.item = Item.create(acknowledgement=self.ack, **self.item_data)
def setUp(self): # création de l'admin admin = User.objects.create_user('admin', password='******') admin.is_staff = True admin.save() # création d'une catégorie c1 = Category(name="Catégorie test 1") c1.save() # création des produits f1 = File(open("media/tests/icon-test1.png", "rb")) with f1: p1 = Product(name="Prod1", description="desc", image=f1, category=c1) p1.save() f2 = File(open("media/tests/icon-test2.png", "rb")) with f2: p2 = Product(name="Prod2", description="desc", image=f2, category=c1) p2.save()
def rubricator(request): rubric_id = request.GET.get("rubric", None) rubric = None rubrics = Rubric.get_published_rubrics().filter(parent=None) if rubric_id is not None : try: rubric = Rubric.objects.get(id=rubric_id) except Rubric.DoesNotExist : return error(request, u"Нет рубрики с таким идентификатором!", u"") rubricator_path = [] parents_id = [] rubrics_view = rubrics products = Product.get_published_products() products_count = products.count() if rubric is not None : rubricator_path = rubric.rubricator_path() parents_id = map(lambda r: r.id, rubricator_path) all_children = rubric.get_all_published_children() products = products.filter(Q(rubrics__in=all_children)|Q(rubrics__in=[rubric])) rubrics_view = all_children if len(rubrics_view) : products = products.order_by("?")[:21] else: products_count = products.count() paginator = Paginator(products, 21) page = request.GET.get('page') try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) else: products = products.order_by("?")[:21] return render_to_response("rubrics/rubrics.html", {'main': rubric, 'products':products, 'products_count':products_count, 'rubrics_view':rubrics_view, 'rubrics':rubrics, 'parents_id':parents_id, 'rubricator_path':rubricator_path}, get_context(request))
def create(self, validated_data): products = validated_data.pop('products', None) agent = Agent.objects.create(**validated_data) agent.save() if products is not None: for product in products: prod = Product() prod.name = product.get('name') prod.category = product.get('category') prod.owner = product.get('owner') prod.save() agent.products.add(prod) agent.save() return agent
for beer in beers: print "Beer: %s" % beer page_url = None results = None try: fd = urlopen(wikipedia_search % beer.replace(' ', '+')) _, results = json.loads(fd.read()) if not len(results): raise Exception('No results') except Exception, e: print 'Woops: %s' % (str(e),) # Select page if results: page = results[0] filtered = [r for r in results if u'bi\xe8re' in r] page = len(filtered) == 1 and filtered[0] or results[0] page_url = wikipedia_article % page.replace(' ', '_') # Add beer try: b = Product(name=beer, category=category, creator=owner) if page_url is not None: b.wikipedia = page_url b.save() print 'Created beer #%d %s ' % (b.id, b.slug) except Exception, e: print 'Already exist : %s' % (str(e),) print 20*'-'
def index(request): # newest 6 created listings can go here OR we can have featured products products = Product.listing().filter(featured=True)[:6] return render_to_response("pages/index.html", locals(), context_instance=RequestContext(request))
def saveProductData(request, productForm): product = Product() product.name = productForm.cleaned_data['name'] product.description = productForm.cleaned_data['description'] product.q_amount = productForm.cleaned_data['q_amount'] user = request.user product.id_owner = user product.start_datetime = str(datetime.now()) product.end_datetime = str(datetime.now()) product.follower_qty = 0 product.visit_qty = 0 product.img = uuid.uuid1().hex product.featured_time = 0; product.active = 1 return product
def tracker(request, is_isa=False, form_class=TIMRateTrackerForm, template_file='thisismoney/ratetracker/wizard.html'): """ """ empty_values = ['', ' ', None, 0] context = _init_context(is_isa) success_view = _get_success_view(is_isa) if request.method == 'POST': if SEARCH in request.POST.keys(): # The wizard forks depending on which product type was selected, we need to check what # was in the request keys form = form_class(request.POST) if form.is_valid(): # bog standard searching if not form.set_reminder: request.session[constants.RESULTS] = constants.RT_RESULTS form_email = form.cleaned_data.get('email') # if the form is valid we want to then display the results.html template_file = 'thisismoney/ratetracker/results.html' if not is_isa else 'thisismoney/isatracker/isa_results.html' selected_product = get_object_or_404(Product, pk=form.cleaned_data.get('product')) context['selected_product'] = selected_product bestbuy = BestBuy.objects.get(pk=form.cleaned_data.get('account_type')) context['bestbuy_type'] = bestbuy # set up the Product Form to Track this product initial = {'provider': selected_product.provider, 'account_type': form.cleaned_data.get('account_type'), 'product': selected_product, 'balance': form.cleaned_data.get('balance'), 'notice': selected_product.notice, 'bonus_term': selected_product.bonus_term, } #set up the registration form initialDetails = {'username': form.cleaned_data.get('email'), 'email': form.cleaned_data.get('email'), 'email2': form.cleaned_data.get('email'), 'password2': 'doesnotmatterjustneededforformisvalid', 'salutation': 'Mr', 'source': 'This is Money', 'uuid': create_uid_next(form), } if selected_product.bonus_term not in empty_values: # wtf this is a float? initial['bonus_term'] = selected_product.bonus_term context['track_product_form'] = ProductReminderForm(initial=initial) context['register_form'] = SCRegistrationForm(initial=initialDetails) product_rate = selected_product.get_rate(datetime.datetime.now().date()) context['rate'] = product_rate #store user in TiMSignups new_signup = TiMSignups(email=form.cleaned_data.get('email'), completed_signup=False) if not TiMSignups.objects.filter(email=form.cleaned_data.get('email')).exists(): new_signup.save() filters = {'%s__gte' % Product.get_ordering(bestbuy.slug): 1} products = Product.objects.filter(bestbuy_type__pk=form.cleaned_data.get('account_type')) \ .filter(**filters).order_by(Product.get_ordering(bestbuy.slug)) \ .filter(minimum__lte=form.cleaned_data.get('balance')) if 'variable-rate-isa' in bestbuy.slug: products = products.filter(is_isa_transfers_in=True) try: your_interest_balance = form.cleaned_data.get('balance') * (product_rate / 100) except: your_interest_balance = 0 if products and len(products) > 0: context['suggested_product'] = products[0] suggested_interest_balance = form.cleaned_data.get('balance') * (products[0].gross_rate / 100) context['suggested_interest_amount'] = suggested_interest_balance + form.cleaned_data.get( 'balance') context['extra_interest'] = suggested_interest_balance - your_interest_balance context['your_interest_amount'] = your_interest_balance + form.cleaned_data.get('balance') else: # form is valid so we copy straight across from one to another # TODO now needs to check if they are logged in if not request.user.is_authenticated(): context = RequestContext(request) new_signup = TiMSignups(email=form.cleaned_data.get('email'), completed_signup=False) if not TiMSignups.objects.filter(email=form.cleaned_data.get('email')).exists(): new_signup.save() data = {'username': MakeUsername(), 'provider': form.cleaned_data.get('provider'), 'account_type': form.cleaned_data.get('account_type'), 'balance': form.cleaned_data.get('balance'), 'maturity_date': form.cleaned_data.get('maturity_date'), 'email': form.cleaned_data.get('email'), 'source': 'This is Money'} context['form'] = TIMFixedRegistrationForm(initial=data) template_file = 'thisismoney/registration_form.html' return render_to_response(template_file, context) else: return HttpResponseRedirect(redirect_to=reverse('home')) else: form = form_class() else: form = form_class() context.update({'TEMPLATE': template_file, 'ratetracker_form': form}) return context
def _product(self, item): try: product = Product.objects.get(id=int(item['id'])) except Product.DoesNotExist: product = Product(id=int(item['id'])) quantity = int(item.get('qtyi', 0)) if quantity < 0: quantity = 0 weight = int(item.get('weight', 0)) if weight < 0: weight = 0 product.sku = item['article'] product.weight = weight product.quantity = quantity product.code = item['link'] product.title = item['name'] product.description = item['descr'] product.is_visible = bool(int(item['pub'])) product.is_wholesale = False product.created = TIMEZONE.localize(datetime.datetime.fromtimestamp(int(item['dt']))) size = None try: size = SIZE_RE.findall(u' '.join([item['name'], item.get('alt', ''), item['descr']]))[0] except IndexError: try: size = SIZE2_RE.findall(u' '.join([item['name'], item.get('alt', ''), item['descr']]))[0] except IndexError: pass if size: product.size = u'×'.join([str(x) for x in size]) return product
def handle(self, *args, **options): """ Scrapes and stores product information """ # get beer page html and make soup object html = urllib2.urlopen(TOP_URL + "/beers/search") soup_beers = BeautifulSoup(html) # find all beers beers = soup_beers.find_all("a", "brand-link") for beer in beers: # get beer page and make soup object beer_url = beer["href"] beer_html = urllib2.urlopen(TOP_URL + beer_url) soup_beer = BeautifulSoup(beer_html) # get sizes beer_products = soup_beer.find_all("table", "brand-pricing") # get propertis and valus and merge them into dict labels = soup_beer.dl.find_all("dt") details = soup_beer.dl.find_all("dd") beer_details = dict(zip(labels,details)) # get name and image beer_name = soup_beer.find("div", "only-desktop").find("h1", "page-title").get_text() beer_image = soup_beer.find("div","brand-image").img["src"] # get country and type beer_attributes = soup_beer.find("p","introduction").find_all("span") beer_attributes = beer_attributes[::-1] beer_country = beer_attributes[0].get_text() beer_type = beer_attributes[1].get_text() # loop through beer products for beer_product in beer_products: beer_containers = beer_product.find_all("tbody") # loop through container tables for beer_container in beer_containers: beer_sizes = beer_container.find_all("tr") # loop through container sizes for beer_size in beer_sizes: # get product information beer_ids = beer_size.a["href"].split('=')[1] beer_id = beer_ids.split('-')[0] print beer_id beer_product_id = beer_ids.split('-')[1] # Comment to disable monitoring beer_product_size = beer_size.find("td","size").get_text() beer_product_price = beer_size.find("td","price").get_text() # check if product exists # NOTE: used this custom solution because django get_or_create # doesn't play nice with custom primary keys try: product_entry = Product.objects.get(product_id=int(beer_product_id.strip())) except: product_entry = Product() # set fields product_entry.name = beer_name.strip() product_entry.size = beer_product_size.strip() product_entry.beer_id = int(beer_id.strip()) product_entry.product_id = int(beer_product_id.strip()) product_entry.image_url = beer_image.strip() product_entry.country = beer_country.strip() product_entry.type = beer_type.strip() # set product attributes # NOTE: this code was created befor the beer store redesign # it still works but some items no longer exist so they were # temporarily omitted from the serializer for key, value in beer_details.iteritems(): attr = key.get_text()[:-1] val = value.get_text() if attr == 'Category': product_entry.category = val if attr == 'Alcohol Content (ABV)': product_entry.abv = float(val[:-1]) if attr == 'Style': product_entry.style= val if attr == 'Attributes': product_entry.attributes= val if attr == 'Brewer': product_entry.brewer= val # update pricing info try: product_entry.price = float(beer_product_price.strip()[1:]) product_entry.on_sale = False except: product_entry.price = float(beer_product_price.split('sale')[1].strip()[1:]) product_entry.on_sale = True product_entry.save()
def setUp(self): prodcutgroup = ProductGroup(name="test product group") prodcutgroup.save() product = Product(product_variation="regular", goss_price="120.00", tax = "0.1200", stock=10, product_group = prodcutgroup) product.save() self.product = product
def get_or_create_product(asin): """ Checks the database for an existing ASIN. If not found, try to fetch it using the Amazon Product API. :return: An instance of `products.models.Product` """ try: product = Product.objects.get(asin=asin) except: amazon = AmazonAPI(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY, settings.AWS_ASSOCIATE_TAG) az = amazon.lookup(ItemId=asin) product = Product(asin=asin, upc=az.upc, ean=az.ean, description=az.title, image_url=az.large_image_url, amazon_url=az.offer_url) product.save() generate_thumb.delay(product, '600x400') generate_thumb.delay(product, '125x125') product.manufacturer = az.get_attribute('Manufacturer') product.brand = az.get_attribute('Brand') product.model_number = az.get_attribute('Model') product.mpn = az.mpn product.part_number = az.part_number product.sku = az.sku product.isbn = az.isbn product.length = az.get_attribute('ItemDimensions.Length') product.width = az.get_attribute('ItemDimensions.Width') product.height = az.get_attribute('ItemDimensions.Height') product.weight = az.get_attribute('ItemDimensions.Weight') product.save() return product
class TestPayPalIPN(TestCase): def setUp(self): self.ipn_record = IPNRecord( transaction_id=1, data='a=1', ) self.ipn_record.save() self.order = Order( donation=100, status=Order.SHOPPING_CART, ) self.order.save() self.product = Product( name='Test Product', slug='test-product', price=500, tax_deductible=50, min_quantity=0, max_quantity=10, current_quantity=5, status=Product.FOR_SALE, ) self.product.save() self.product_in_order = ProductInOrder( order=self.order, product=self.product, quantity=1, ) self.product_in_order.save() def test_ipn_error_conditions(self): # Anything besides POST gets a 404 response = self.client.get('/paypal/ipn/') self.assertEqual(response.status_code, 404) # Can't verify message with PayPal response = self.client.post('/paypal/ipn/', {}) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Ok (unverified)') # Message not for our business response = self.client.post('/paypal/ipn/', { '_fake_paypal_verification': settings.SECRET_KEY, 'business': '*****@*****.**', }) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Ok (wrong business)') # No transaction ID provided response = self.client.post('/paypal/ipn/', { '_fake_paypal_verification': settings.SECRET_KEY, 'business': settings.PAYPAL_BUSINESS, }) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Ok (no id)') # Duplicate IPN message received response = self.client.post('/paypal/ipn/', { '_fake_paypal_verification': settings.SECRET_KEY, 'business': settings.PAYPAL_BUSINESS, 'txn_id': '1', }) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Ok (duplicate)') # Status is not Completed response = self.client.post('/paypal/ipn/', { '_fake_paypal_verification': settings.SECRET_KEY, 'business': settings.PAYPAL_BUSINESS, 'txn_id': '2', 'payment_status': 'Waiting', }) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Ok (not completed)') # No matching order response = self.client.post('/paypal/ipn/', { '_fake_paypal_verification': settings.SECRET_KEY, 'business': settings.PAYPAL_BUSINESS, 'txn_id': '3', 'payment_status': 'Completed', }) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Ok (no order)') # Payment for wrong amount response = self.client.post('/paypal/ipn/', { '_fake_paypal_verification': settings.SECRET_KEY, 'business': settings.PAYPAL_BUSINESS, 'txn_id': '4', 'payment_status': 'Completed', 'invoice': self.order.invoice_id, 'mc_gross': '1.00', }) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Ok (wrong amount)') def test_ipn_success_conditions(self): # Order marked as paid response = self.client.post('/paypal/ipn/', { '_fake_paypal_verification': settings.SECRET_KEY, 'business': settings.PAYPAL_BUSINESS, 'txn_id': '5', 'payment_status': 'Completed', 'invoice': self.order.invoice_id, 'mc_gross': '646.25', }) order = Order.objects.get(pk=self.order.id) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Ok') self.assertEqual(order.status, Order.PAYMENT_CONFIRMED) record = IPNRecord.objects.get(transaction_id='5') self.assertTrue(record.data)
def generate_sampledata(options): # Create the top 10 topics used topic(title='Learn the Basics: get started', slug='get-started', save=True) topic(title='Download, install and migration', slug='download-and-install', save=True) topic(title='Privacy and security settings', slug='privacy-and-security', save=True) topic(title='Customize controls, options and add-ons', slug='customize', save=True) topic(title='Fix slowness, crashing, error messages and other problems', slug='fix-problems', save=True) topic(title='Tips and tricks', slug='tips', save=True) topic(title='Bookmarks', slug='bookmarks', save=True) topic(title='Cookies', slug='cookies', save=True) topic(title='Tabs', slug='tabs', save=True) topic(title='Websites', slug='websites', save=True) topic(title='Hot topics', slug='hot', save=True) # There are two products in our schema try: firefox = Product.objects.get(slug='firefox') except Product.DoesNotExist: # Note: This matches migration 156. When run in the tests, the # migrations don't happen. firefox = Product(title='Firefox', description='Web browser for Windows, Mac and Linux', display_order=1, visible=True, slug='firefox') firefox.save() try: mobile = Product.objects.get(slug='mobile') except Product.DoesNotExist: # Note: This matches migration 156. When run in the tests, the # migrations don't happen. mobile = Product(title='Firefox for Mobile', description='Web browser for Android smartphones and tablets', display_order=2, visible=True, slug='mobile') mobile.save() # Create the special documents that are linked to from the home page moznews = document(title='Mozilla News', slug='mozilla-news', save=True) revision(content=MOZILLA_NEWS_CONTENT, document=moznews, is_approved=True, reviewed=datetime.now(), save=True) suggestion = document(title='Suggestion Box', slug='suggestion-box', save=True) revision(content=SUGGESTION_BOX_CONTENT, document=suggestion, is_approved=True, reviewed=datetime.now(), save=True) superheroes = document(title='Superheroes Wanted!', slug='superheroes-wanted', save=True) revision(content=SUPERHEROES_CONTENT, document=superheroes, is_approved=True, reviewed=datetime.now(), save=True) community = document(title='Get community support', slug='get-community-support', save=True) revision(content=COMMUNITY_CONTENT, document=community, is_approved=True, reviewed=datetime.now(), save=True) # Create a hot article flash = document(title='Flash 11.3 crashes', slug='flash-113-crashes', save=True) revision(content=FLASH_CONTENT, document=flash, is_approved=True, reviewed=datetime.now(), save=True) flash.products.add(firefox) flash.topics.add(Topic.objects.get(slug='fix-problems')) flash.topics.add(Topic.objects.get(slug='hot')) # Generate 9 sample documents with 2 topics each topics = list(Topic.objects.all()) for i in xrange(9): d = document(title='Sample Article %s' % str(i + 1), slug='sample-article-%s' % str(i + 1), save=True) revision(document=d, is_approved=True, reviewed=datetime.now(), save=True) d.products.add(firefox) d.products.add(mobile) d.topics.add(topics[i]) d.topics.add(topics[i + 1])
def setUp(self): """ Set up for the Acknowledgement Test Objects created: -User -Customer -Supplier -Address -product -2 fabrics After Creating all the needed objects for the Acknowledgement, test that all the objects have been made. """ super(ShippingResourceTest, self).setUp() self.ct = ContentType(app_label="shipping") self.ct.save() #Create the user self.username = '******' self.password = '******' self.user = User.objects.create_user(self.username, '*****@*****.**', self.password) self.user.save() p = Permission(content_type=self.ct, codename="change_shipping") p.save() p2 = Permission(content_type=self.ct, codename="add_shipping") p2.save() self.user.user_permissions.add(p) self.user.user_permissions.add(p2) self.user.save() self.setup_client() #Create supplier, customer and addrss self.customer = Customer(**base_customer) self.customer.save() self.supplier = Supplier(**base_supplier) self.supplier.save() self.address = Address(address1="Jiggle", contact=self.customer) self.address.save() #Create project self.project = Project.objects.create(codename="Ladawan") #Create phase self.phase = Phase.objects.create(description="Phase 1/6", project=self.project) #Create a product to add self.product = Product.create(self.user, **base_product) self.product.save() self.fabric = Fabric.create(**base_fabric) f_data = base_fabric.copy() f_data["pattern"] = "Stripe" self.fabric2 = Fabric.create(**f_data) #Create acknowledgement ack_data = base_ack.copy() del ack_data['customer'] del ack_data['items'] del ack_data['employee'] self.ack = Acknowledgement(**ack_data) self.ack.customer = self.customer self.ack.employee = self.user self.ack.save() #Create an item item_data = {'id': 1, 'quantity': 1, 'is_custom_size': True, 'width': 1500, "fabric": {"id":1}} self.item = AckItem.create(acknowledgement=self.ack, **item_data) #Create an item item_data = {'id': 1, 'quantity': 2, 'is_custom_size': True, 'width': 1500, "fabric": {"id":1}} self.item2 = AckItem.create(acknowledgement=self.ack, **item_data)