def handle(self, *args, **options): p = Product.objects.all() p.delete() c = Category.objects.all() c.delete() categories = [ {'name': 'Сливочное'}, {'name': 'Щербет'}, {'name': 'Фруктовый лёд'}, {'name': 'Мелорин'} ] for item in categories: item = Category(**item) item.save() products = [ {'name': 'Сливочное с апельсиновым джемом и цитрусовой стружкой', 'price': 310, 'photo': 'products/item_1.jpg', 'category_id': Category.objects.get(name='Сливочное'), 'is_hit': 0, 'is_new': 1}, {'name': 'Сливочно-кофейное с кусочками шоколада', 'price': 380, 'photo': 'products/item_2.jpg', 'category_id': Category.objects.get(name='Сливочное'), 'is_hit': 0, 'is_new': 1}, {'name': 'Сливочно-клубничное с присыпкой из белого шоколада', 'price': 355, 'photo': 'products/item_3.jpg', 'category_id': Category.objects.get(name='Сливочное'), 'is_hit': 0, 'is_new': 1}, {'name': 'Сливочное крем-брюле с карамельной подливкой', 'price': 415, 'photo': 'products/item_4.jpg', 'category_id': Category.objects.get(name='Сливочное'), 'is_hit': 0, 'is_new': 1}, {'name': 'Сливочное с брусничным джемом', 'price': 325, 'photo': 'products/item_5.jpg', 'category_id': Category.objects.get(name='Сливочное'), 'is_hit': 0, 'is_new': 1}, {'name': 'Сливочно-черничное с цельными ягодами черники', 'price': 410, 'photo': 'products/item_6.jpg', 'category_id': Category.objects.get(name='Сливочное'), 'is_hit': 0, 'is_new': 1}, {'name': 'Сливочно-лимонное с карамельной присыпкой', 'price': 375, 'photo': 'products/item_7.jpg', 'category_id': Category.objects.get(name='Сливочное'), 'is_hit': 0, 'is_new': 1}, {'name': 'Сливочное с шоколадной стружкой', 'price': 320, 'photo': 'products/item_8.jpg', 'category_id': Category.objects.get(name='Сливочное'), 'is_hit': 0, 'is_new': 1}, {'name': 'Сливочно ванильное с кусочками шоколада', 'price': 440, 'photo': 'products/item_9.jpg', 'category_id': Category.objects.get(name='Сливочное'), 'is_hit': 0, 'is_new': 1}, {'name': 'Сливочное с ментоловым сиропом', 'price': 435, 'photo': 'products/item_10.jpg', 'category_id': Category.objects.get(name='Сливочное'), 'is_hit': 0, 'is_new': 1}, {'name': 'Сливочное с кусочками черного шоколада', 'price': 355, 'photo': 'products/item_11.jpg', 'category_id': Category.objects.get(name='Сливочное'), 'is_hit': 0, 'is_new': 1}, {'name': 'Сливочное с мятным сиропом', 'price': 420, 'photo': 'products/item_12.jpg', 'category_id': Category.objects.get(name='Сливочное'), 'is_hit': 0, 'is_new': 1}, ] for item in products: item = Product(**item) item.save()
def get_populate_categories(self): """ Method to populate all categories containing greater than or equal to 5000 products Args: url_categories (string): endpoint Open Food Facts Api for categories Returns: list: all categories selected """ url_categories = "https://fr.openfoodfacts.org/categories.json" print("Requesting categories") category_response = requests.get(url=url_categories) if category_response.status_code != 200: self.stdout.write( self.style.ERROR( "Searching for category with the Open Food Facts API is not available." )) categories = json.loads(category_response.content)["tags"] categories_selected = [ categ for categ in categories if categ["products"] >= 3000 ] for category in categories_selected: try: with transaction.atomic(): categ = Category(name=category["name"]) categ.save() except Exception as exx: print( "Une des catégories n'a pu être importée, voici l'erreur:", exx) return categories_selected
def handle(self, *args, **options): try: products = list() with open(settings.MODIFIED_CSV, newline="") as r: reader = csv.DictReader(r, delimiter=";") products_categories = list() for row in reader: product_data = dict() for field in PRODUCT_FIELDS: if field in [ "fat_100g", "saturated_fat_100g", "sugars_100g", "salt_100g", ]: if row[field].isdigit(): product_data[field] = Decimal(row[field]) elif not row[field]: product_data[field] = Decimal("0") elif field == "categories_tags": categories = row[field].split(",") category_obj_lst = list() for category in categories: category = (normalize("NFKD", category).encode( "ASCII", "ignore").decode().lower()[3:]) category_qs = Category.objects.filter( name=category) if category_qs: category_obj_lst.append( category_qs.first()) else: category_obj = Category(name=category) category_obj.save() category_obj_lst.append(category_obj) else: product_data[field] = (normalize( "NFKD", row[field]).encode("ASCII", "ignore").decode().lower()) already_added = [ product for product in products if product.product_name == product_data["product_name"] ] if not already_added: products_categories.append(category_obj_lst) products.append(Product(**product_data)) Product.objects.bulk_create(products) products = Product.objects.all().order_by("id") for product, category_list in zip(products, products_categories): product.categories.set(category_list) product.save() except Exception as e: raise CommandError(f"Something went wrong.\n{e}") self.stdout.write( self.style.SUCCESS( "Successfully imported data from CSV to database."))
def create_category(name, parent_name): if parent_name is not None: parent_category = Category.objects.get(name=parent_name) return parent_category.category_set.create(name=name) else: # if category has no parent new_category = Category() new_category.name = name new_category.save() return new_category
def createcategory(request): #data = request.GET categories = Category.objects.all() if request.method == "POST": data=request.POST cat = Category(name=data.get("cat_name")) cat.save() return redirect("/") return render(request, "product/createcategory.html", {"categories":categories})
def insert_category_in_db(self): """ Insert category """ try: data = Category(name=self.category) data.save() if STDOUT: self.stdout.write(self.style.SUCCESS( 'Category : "%s", Insertion OK' % self.category) ) except IntegrityError: if STDOUT: self.stdout.write(self.style.WARNING( 'Category : "%s", Insertion FAIL (IntegrityError)' % self.category))
def handle(self, **options): categories = [ ("کلاه", "انواع کلاه ها با رنگبندی های مختلف برای آقایان و بانوان"), ("عینک", "عینک های آفتابی متنوع با کیفیت عالی"), ("ساعت مچی", "ساعت مچی متناسب برای زیباپسندان"), ("انگشتر", "انواع انگشتر های زیبا و جذاب"), ("کیف پول", "انواع کیف پول پارچه ای و چرمی "), ] for category_data in categories: c = Category() c.title, c.description = category_data c.save() hat_images_path = path.join(settings.BASE_DIR, "media", "hat") pictures = [f for f in os.listdir(hat_images_path) if path.isfile(os.path.join(hat_images_path, f))] hat_product_data = [ ("چنار", "کلاه ساده و زیبا", 12000), ("روزگار", "یک کلاه متفاوت و زیبا", 16000), ("یادگار", "سازگار با هر نوع تیپ", 20000), ("نوین", "شکلی و ساده", 10000), ("جوانی", "کلاه مناسب نسل جوان", 22000), ("سحاب", "کلاه خاص برای افراد خاص", 18000), ("چنار", "کلاه ساده و زیبا", 12000), ("روزگار", "یک کلاه متفاوت و زیبا", 16000), ("یادگار", "سازگار با هر نوع تیپ", 20000), ("نوین", "شکلی و ساده", 10000), ("جوانی", "کلاه مناسب نسل جوان", 22000), ("سحاب", "کلاه خاص برای افراد خاص", 18000), ("چنار", "کلاه ساده و زیبا", 12000), ("روزگار", "یک کلاه متفاوت و زیبا", 16000), ("یادگار", "سازگار با هر نوع تیپ", 20000), ("نوین", "شکلی و ساده", 10000), ("جوانی", "کلاه مناسب نسل جوان", 22000), ("سحاب", "کلاه خاص برای افراد خاص", 18000), ] hat_category = Category.objects.filter(pk=1).first() for hat in hat_product_data: p = Product() p.name, p.description, p.price = hat p.category = hat_category p.save() pic = Picture() pic.path.name = "hat/" + pictures.pop() pic.product = p pic.save()
def feed_db(self, raw_products): style = color.make_style() stdout = base.OutputWrapper(sys.stdout) self._clear_db() # Insert each product in the application's database stdout.write("==== Insert products in the database ====") stdout.write("Inserting products in the database...") for raw_product in raw_products: serialized_product = self._serialize_product(raw_product) try: product = Product( code=serialized_product["code"], name=serialized_product["name"], url=serialized_product["url"], nutriscore_grade=serialized_product["nutriscore_grade"], image_url=serialized_product["image_url"], image_small_url=serialized_product["image_small_url"], salt_100=serialized_product["salt_100"], sugars_100=serialized_product["sugars_100"], saturated_fat_100=serialized_product["saturated_fat_100"], fat_100=serialized_product["fat_100"], ) product.full_clean() except ValidationError: # Ignore products with ValidationError continue product.save() # Insert associated categories, stores and brands for category in serialized_product["categories"]: try: obj = Category.objects.get(name=category) except ObjectDoesNotExist: try: obj = Category(name=category) obj.full_clean() except ValidationError: # Ignore categories with ValidationError continue obj.save() product.categories.add(obj) stdout.write(style.SUCCESS("DONE")) stdout.write("==============================================")
def other_request(request): post_data = request.POST get_data = request.GET # print(post_data) # print(get_data) if 'name' and 'option' in post_data: if post_data['option'] == 'category': new_category = Category(name=post_data['name'], remarks=post_data['remarks'], isPendingForApproval=False) new_category.save() elif post_data['option'] == 'type': new_type = Type(name=post_data['name'], remarks=post_data['remarks']) new_type.save() elif post_data['option'] == 'brand': new_brand = Brand(name=post_data['name'], remarks=post_data['remarks'], isPendingForApproval=False) new_brand.save() all_categories = Category.objects.all() all_types = Type.objects.all() all_brands = Brand.objects.all() if 'toggle' and 'item' in get_data: package_id = get_data['toggle'] if get_data['item'] == 'category': this_package = Category.objects.get(id=package_id) elif get_data['item'] == 'type': print('here') this_package = Type.objects.get(id=package_id) elif get_data['item'] == 'brand': this_package = Brand.objects.get(id=package_id) if this_package.isActive: this_package.isActive = False else: this_package.isActive = True this_package.save() return redirect('/other_request') else: return render(request, 'admin/other_requests.sho', {'all_categories': all_categories, 'all_types': all_types, 'all_brands': all_brands})
def update_categories(self, product, add=True): """ Helper method for allowing the archive item to decide which categories to include the product in. Called after the product including price and attributes have been created. Must return a list of categories created or added to product. """ try: category = Category.objects.get(site=Site.objects.get_current(), slug=self._get_subtype().lower()) except Category.DoesNotExist: category = Category(site=Site.objects.get_current(), slug=self._get_subtype().lower(), name=unicode( self._meta.verbose_name_plural).title()) category.save() if add: product.category.add(category) return [category]
def handle_noargs(self, **options): from satchmo_store.contact.models import ( AddressBook, Contact, ContactOrganization, ContactOrganizationRole, ContactRole, Organization, PhoneNumber, ) from product.models import ( Category, OptionGroup, Option, Price, Product, ) from product.modules.configurable.models import ConfigurableProduct from satchmo_store.shop.models import Config from django.conf import settings from l10n.models import Country from django.contrib.sites.models import Site from django.contrib.auth.models import User #idempotency test print "Checking for existing sample data." try: p = Product.objects.get(slug="dj-rocks") print "It looks like you already have loaded the sample store data, quitting." import sys sys.exit(1) except Product.DoesNotExist: pass print "Loading sample store data." #Load basic configuration information print "Creating site..." try: site = Site.objects.get(id=settings.SITE_ID) print "Using existing site #%i" % settings.SITE_ID except Site.DoesNotExist: print "Creating Example Store Site" site = Site(domain="localhost", name="Sample Store") site.domain = settings.SITE_DOMAIN site.name = settings.SITE_NAME site.save() try: store_country = Country.objects.get(iso3_code='USA') except Country.DoesNotExist: print "\nError: Country data should be first loaded by: python manage.py satchmo_load_l10n" import sys sys.exit(1) config = Config(site=site, store_name=settings.SITE_NAME, country=store_country, sales_country=store_country) config.save() config.shipping_countries.add(store_country) config.save() print "Creating Customers..." # Import some customers customer = ContactRole.objects.get(pk='Customer') c1 = Contact(first_name="Chris", last_name="Smith", email="*****@*****.**", role=customer, notes="Really cool stuff") c1.save() p1 = PhoneNumber(contact=c1, phone="601-555-5511", type="Home", primary=True) p1.save() c2 = Contact(first_name="John", last_name="Smith", email="*****@*****.**", role=customer, notes="Second user") c2.save() p2 = PhoneNumber(contact=c2, phone="999-555-5111", type="Work", primary=True) p2.save() # Import some addresses for these customers us = Country.objects.get(iso2_code='US') a1 = AddressBook(description="Home", street1="8235 Pike Street", city="Anywhere Town", state="TN", postal_code="38138", country=us, is_default_shipping=True, contact=c1) a1.save() a2 = AddressBook(description="Work", street1="1245 Main Street", city="Stillwater", state="MN", postal_code="55082", country=us, is_default_shipping=True, contact=c2) a2.save() print "Creating Suppliers..." #Import some suppliers supplier = ContactOrganizationRole.objects.get(pk='Supplier') company = ContactOrganization.objects.get(pk='Company') contactsupplier = ContactRole.objects.get(pk='Supplier') org1 = Organization(name="Rhinestone Ronny", type=company, role=supplier) org1.save() c4 = Contact(first_name="Fred", last_name="Jones", email="*****@*****.**", role=contactsupplier, organization=org1) c4.save() p4 = PhoneNumber(contact=c4, phone="800-188-7611", type="Work", primary=True) p4.save() p5 = PhoneNumber(contact=c4, phone="755-555-1111", type="Fax") p5.save() a3 = AddressBook(contact=c4, description="Mailing address", street1="Receiving Dept", street2="918 Funky Town St", city="Fishkill", state="NJ", country=us, postal_code="19010") a3.save() #s1 = Supplier(name="Rhinestone Ronny", address1="918 Funky Town St", address2="Suite 200", # city="Fishkill", state="NJ", zip="19010", phone1="800-188-7611", fax="900-110-1909", email="*****@*****.**", # notes="My main supplier") #s1.save() #s2 = Supplier(name="Shirt Sally", address1="9 ABC Lane", # city="Happyville", state="MD", zip="190111", phone1="888-888-1111", fax="999-110-1909", email="*****@*****.**", # notes="Shirt Supplier") #s2.save() print "Creating Categories..." #Create some categories cat1 = Category(site=site, name="Shirts", slug="shirts", description="Women's Shirts") cat1.save() cat2 = Category(site=site, name="Short Sleeve", slug="shortsleeve", description="Short sleeve shirts", parent=cat1) cat2.save() cat3 = Category(site=site, name="Books", slug="book", description="Books") cat3.save() cat4 = Category(site=site, name="Fiction", slug="fiction", description="Fiction Books", parent=cat3) cat4.save() cat5 = Category(site=site, name="Science Fiction", slug="scifi", description="Science Fiction", parent=cat4) cat5.save() cat6 = Category(site=site, name="Non Fiction", slug="nonfiction", description="Non Fiction", parent=cat3) cat6.save() cat7 = Category(site=site, name="Software", slug="software") cat7.save() print "Creating products..." #Create some items i1 = Product(site=site, name="Django Rocks shirt", slug="dj-rocks", description="Really cool shirt", active=True, featured=True) i1.save() p1 = Price(price="20.00", product=i1) p1.save() i1.category.add(cat1) i1.save() i2 = Product( site=site, name="Python Rocks shirt", slug="PY-Rocks", description="Really cool python shirt - One Size Fits All", active=True, featured=True) i2.save() p2 = Price(price="19.50", product=i2) p2.save() i2.category.add(cat2) i2.save() i3 = Product(site=site, name="A really neat book", slug="neat-book", description="A neat book. You should buy it.", active=True, featured=True) i3.save() p3 = Price(price="5.00", product=i3) p3.save() i3.category.add(cat4) i3.save() i4 = Product(site=site, name="Robots Attack!", slug="robot-attack", description="Robots try to take over the world.", active=True, featured=True) i4.save() p4 = Price(price="7.99", product=i4) p4.save() i4.category.add(cat5) i4.save() # i5 = Product(site=site, name="Really Neat Software", slug="neat-software", description="Example Configurable/Downloadable product", active=True, featured=True) # i5.save() # i5.category.add(cat7) # i5.save() #Create an attribute set optSet1 = OptionGroup(site=site, name="sizes", sort_order=1) optSet2 = OptionGroup(site=site, name="colors", sort_order=2) optSet1.save() optSet2.save() optSet3 = OptionGroup(site=site, name="Book type", sort_order=1) optSet3.save() optSet4 = OptionGroup(site=site, name="Full/Upgrade", sort_order=5) optSet4.save() optItem1a = Option(name="Small", value="S", sort_order=1, option_group=optSet1) optItem1a.save() optItem1b = Option(name="Medium", value="M", sort_order=2, option_group=optSet1) optItem1b.save() optItem1c = Option(name="Large", value="L", sort_order=3, price_change="1.00", option_group=optSet1) optItem1c.save() optItem2a = Option(name="Black", value="B", sort_order=1, option_group=optSet2) optItem2a.save() optItem2b = Option(name="White", value="W", sort_order=2, option_group=optSet2) optItem2b.save() optItem2c = Option(name="Blue", value="BL", sort_order=3, price_change="2.00", option_group=optSet2) optItem2c.save() optItem3a = Option(name="Hard cover", value="hard", sort_order=1, option_group=optSet3) optItem3a.save() optItem3b = Option(name="Soft cover", value="soft", sort_order=2, price_change="1.00", option_group=optSet3) optItem3b.save() optItem3c = Option(name="On tape", value="tape", sort_order=3, option_group=optSet3) optItem3c.save() optItem4a = Option(name="Full Version", value="full", option_group=optSet4, sort_order=1) optItem4a.save() optItem4b = Option(name="Upgrade Version", value="upgrade", option_group=optSet4, sort_order=2) optItem4b.save() #Add the option group to our items pg1 = ConfigurableProduct(product=i1) pg1.save() pg1.option_group.add(optSet1) pg1.save() pg1.option_group.add(optSet2) pg1.save() pg3 = ConfigurableProduct(product=i3) pg3.save() pg3.option_group.add(optSet3) pg3.save() pg4 = ConfigurableProduct(product=i4) pg4.save() pg4.option_group.add(optSet3) pg4.save() # pg5 = ConfigurableProduct(product=i5) # pg5.option_group.add(optSet4) # pg5.save() print "Creating product variations..." #Create the required sub_items pg1.create_all_variations() pg3.create_all_variations() pg4.create_all_variations() #pg5.create_all_variations() #set prices for full and upgrade versions of neat-software, this is an alternative to using the price_change in options, it allows for more flexability when required. # pv1 = pg5.get_product_from_options([optItem4a]) # Price(product=pv1, price='5.00').save() # Price(product=pv1, price='2.00', quantity='50.00').save() # DownloadableProduct(product=pv1).save() # pv2 = pg5.get_product_from_options([optItem4b]) # Price(product=pv2, price='1.00').save() # DownloadableProduct(product=pv2).save() print "Create a test user..." #First see if our test user is still there, then use or create that user try: test_user = User.objects.get(username="******") except: test_user = User.objects.create_user('csmith', '*****@*****.**', 'test') test_user.save() c1.user = test_user c1.save()
def handle_noargs(self, **options): from satchmo_store.contact.models import ( AddressBook, Contact, ContactOrganization, ContactOrganizationRole, ContactRole, Organization, PhoneNumber, ) from product.models import ( Category, OptionGroup, Option, Price, Product, ) from product.modules.configurable.models import ConfigurableProduct from satchmo_store.shop.models import Config from django.conf import settings from l10n.models import Country from django.contrib.sites.models import Site from django.contrib.auth.models import User #idempotency test print "Checking for existing sample data." try: p = Product.objects.get(slug="dj-rocks") print "It looks like you already have loaded the sample store data, quitting." import sys sys.exit(1) except Product.DoesNotExist: pass print "Loading sample store data." #Load basic configuration information print "Creating site..." try: site = Site.objects.get(id=settings.SITE_ID) print "Using existing site #%i" % settings.SITE_ID except Site.DoesNotExist: print "Creating Example Store Site" site = Site(domain="localhost", name="Sample Store") site.domain = settings.SITE_DOMAIN site.name = settings.SITE_NAME site.save() try: store_country = Country.objects.get(iso3_code='USA') except Country.DoesNotExist: print "\nError: Country data should be first loaded by: python manage.py satchmo_load_l10n" import sys sys.exit(1) config = Config(site=site, store_name=settings.SITE_NAME, country=store_country, sales_country=store_country) config.save() config.shipping_countries.add(store_country) config.save() print "Creating Customers..." # Import some customers customer = ContactRole.objects.get(pk='Customer') c1 = Contact(first_name="Chris", last_name="Smith", email="*****@*****.**", role=customer, notes="Really cool stuff") c1.save() p1 = PhoneNumber(contact=c1, phone="601-555-5511", type="Home",primary=True) p1.save() c2 = Contact(first_name="John", last_name="Smith", email="*****@*****.**", role=customer, notes="Second user") c2.save() p2 = PhoneNumber(contact=c2, phone="999-555-5111", type="Work",primary=True) p2.save() # Import some addresses for these customers us = Country.objects.get(iso2_code='US'); a1 = AddressBook(description="Home", street1="8235 Pike Street", city="Anywhere Town", state="TN", postal_code="38138", country=us, is_default_shipping=True, contact=c1) a1.save() a2 = AddressBook(description="Work", street1="1245 Main Street", city="Stillwater", state="MN", postal_code="55082", country=us, is_default_shipping=True, contact=c2) a2.save() print "Creating Suppliers..." #Import some suppliers supplier = ContactOrganizationRole.objects.get(pk='Supplier') company = ContactOrganization.objects.get(pk='Company') contactsupplier = ContactRole.objects.get(pk='Supplier') org1 = Organization(name="Rhinestone Ronny", type=company, role=supplier) org1.save() c4 = Contact(first_name="Fred", last_name="Jones", email="*****@*****.**", role=contactsupplier, organization=org1) c4.save() p4 = PhoneNumber(contact=c4,phone="800-188-7611", type="Work", primary=True) p4.save() p5 = PhoneNumber(contact=c4,phone="755-555-1111",type="Fax") p5.save() a3 = AddressBook(contact=c4, description="Mailing address", street1="Receiving Dept", street2="918 Funky Town St", city="Fishkill", state="NJ", country=us, postal_code="19010") a3.save() #s1 = Supplier(name="Rhinestone Ronny", address1="918 Funky Town St", address2="Suite 200", # city="Fishkill", state="NJ", zip="19010", phone1="800-188-7611", fax="900-110-1909", email="*****@*****.**", # notes="My main supplier") #s1.save() #s2 = Supplier(name="Shirt Sally", address1="9 ABC Lane", # city="Happyville", state="MD", zip="190111", phone1="888-888-1111", fax="999-110-1909", email="*****@*****.**", # notes="Shirt Supplier") #s2.save() print "Creating Categories..." #Create some categories '''cat1 = Category(site=site, name="Shirts",slug="shirts",description="Women's Shirts") cat1.save() cat2 = Category(site=site, name="Short Sleeve",slug="shortsleeve",description="Short sleeve shirts", parent=cat1) cat2.save()''' cat3 = Category(name="Books",slug="book",description="Books") cat3.save() cat3.site.add(site) '''cat4 = Category(site=site, name="Fiction",slug="fiction",description="Fiction Books", parent=cat3) cat4.save() cat5 = Category(site=site, name="Science Fiction",slug="scifi",description="Science Fiction",parent=cat4) cat5.save() cat6 = Category(site=site, name="Non Fiction",slug="nonfiction",description="Non Fiction",parent=cat3) cat6.save() cat7 = Category(site=site, name="Software", slug="software") cat7.save()''' print "Creating products..." #Create some items '''i1 = Product(name="Django Rocks shirt", slug="dj-rocks", description="Really cool shirt", active=True, featured=True) i1.save() p1 = Price(price="20.00", product=i1) p1.save() i1.category.add(cat1) i1.save() i2 = Product(name="Python Rocks shirt", slug="PY-Rocks", description="Really cool python shirt - One Size Fits All", active=True, featured=True) i2.save() p2 = Price(price="19.50", product=i2) p2.save() i2.category.add(cat2) i2.save()''' i3 = Product(name="Purusha Suktam", slug="Advyata", description="A neat book. You should buy it.", active=True, featured=True) i3.save() i3.site.add(site) p3 = Price(price="5.00", product=i3) p3.save() i3.category.add(cat3) i3.save() i3.site.add(site) '''i4 = Product(name="Robots Attack!", slug="robot-attack", description="Robots try to take over the world.", active=True, featured=True) i4.save() p4 = Price(price="7.99", product=i4) p4.save() i4.category.add(cat5) i4.save() # i5 = Product(site=site, name="Really Neat Software", slug="neat-software", description="Example Configurable/Downloadable product", active=True, featured=True) # i5.save() # i5.category.add(cat7) # i5.save() #Create an attribute set optSet1 = OptionGroup(site=site, name="sizes", sort_order=1) optSet2 = OptionGroup(site=site, name="colors", sort_order=2) optSet1.save() optSet2.save()''' optSet3 = OptionGroup(name="Book type", sort_order=1) optSet3.save() optSet3.site.add(site) '''optSet4 = OptionGroup(site=site, name="Full/Upgrade", sort_order=5) optSet4.save() optItem1a = Option(name="Small", value="S", sort_order=1, option_group=optSet1) optItem1a.save() optItem1b = Option(name="Medium", value="M", sort_order=2, option_group=optSet1) optItem1b.save() optItem1c = Option(name="Large", value="L", sort_order=3, price_change="1.00", option_group=optSet1) optItem1c.save() optItem2a = Option(name="Black", value="B", sort_order=1, option_group=optSet2) optItem2a.save() optItem2b = Option(name="White", value="W", sort_order=2, option_group=optSet2) optItem2b.save() optItem2c = Option(name="Blue", value="BL", sort_order=3, price_change="2.00", option_group=optSet2) optItem2c.save()''' optItem3a = Option(name="Hard cover", value="hard", sort_order=1, option_group=optSet3) optItem3a.save() optItem3b = Option(name="Soft cover", value="soft", sort_order=2, price_change="1.00", option_group=optSet3) optItem3b.save() optItem3c = Option(name="On tape", value="tape", sort_order=3, option_group=optSet3) optItem3c.save() '''optItem4a = Option(name="Full Version", value="full", option_group=optSet4, sort_order=1) optItem4a.save() optItem4b = Option(name="Upgrade Version", value="upgrade", option_group=optSet4, sort_order=2) optItem4b.save()''' #Add the option group to our items '''pg1 = ConfigurableProduct(product=i1) pg1.save() pg1.option_group.add(optSet1) pg1.save() pg1.option_group.add(optSet2) pg1.save()''' pg3 = ConfigurableProduct(product=i3) pg3.save() pg3.option_group.add(optSet3) pg3.save() '''pg4 = ConfigurableProduct(product=i4) pg4.save() pg4.option_group.add(optSet3) pg4.save()''' # pg5 = ConfigurableProduct(product=i5) # pg5.option_group.add(optSet4) # pg5.save() print "Creating product variations..." #Create the required sub_items #pg1.create_all_variations() pg3.create_all_variations() #pg4.create_all_variations() #pg5.create_all_variations() #set prices for full and upgrade versions of neat-software, this is an alternative to using the price_change in options, it allows for more flexability when required. # pv1 = pg5.get_product_from_options([optItem4a]) # Price(product=pv1, price='5.00').save() # Price(product=pv1, price='2.00', quantity='50.00').save() # DownloadableProduct(product=pv1).save() # pv2 = pg5.get_product_from_options([optItem4b]) # Price(product=pv2, price='1.00').save() # DownloadableProduct(product=pv2).save() print "Create a test user..." #First see if our test user is still there, then use or create that user try: test_user = User.objects.get(username="******") except: test_user = User.objects.create_user('csmith', '*****@*****.**', 'test') test_user.save() c1.user = test_user c1.save()
import json from product.models import Category, SubCategory, Item # from djnago.contrib.auth.models import User with open('.json/category.json') as f: template = json.load(f) for newCategory in template: newCategory = Category(name=newCategory['name']) newCategory.save() with open('.json/subcat.json') as f: template2 = json.load(f) for new in template2: new = SubCategory( parent_category=Category.objects.get(name=new['parent_name']), subname=new['subname']) new.save() # NOTE: error opening # with open('.json/items.json') as f: # template3 = json.load(f) # for new in template3: # new = Item(category=Category.objects.get( # name=new['category']), sub_category=SubCategory.objects.get(subname=new['sub_category']), title=new['title'], price=new['price'], content=new['content'], image=new['image'], condition=new['condition'], item_available_for=new['item_available_for'], author=new['author'], date_posted=new['date_posted']) # new.save()
cat2 = Category() cat2.title = "Bluzi" sub2 = Category() sub2.title = "Kusi Bluzi" sub2.parent = cat2 cat3 = Category() cat3.title = "Gashti" sub3 = Category() sub3.title = "Kusi Gashti" sub3.parent = cat3 cat1.save() cat2.save() cat3.save() sub1.save() sub2.save() sub3.save() # opens a file with urls of fake articles profilePicRead = open("generator/profile_pictures.txt", "r+") product_title = open("generator/product_names.txt", 'r+') sentencesRead = open("generator/sentences.txt", "r+") # then makes into an array split by endline articleUrl = profilePicRead.read().split("\n") productTitle = product_title.read().split("\n") sentences = re.findall(r"\s+[^.!?]*[.!?]", sentencesRead.read())
from product.models import Category, Product, ExtraImage from controller.models import Slide from autofixture import AutoFixture from django.contrib.auth.models import User print "Creating categories" entertainment = Category(title="Entertainment", slug="entertainment") entertainment.save() xbox = Category(title="Xbox", parent=entertainment, slug='xbox') xbox.save() games = Category(title="Games", parent=xbox, slug='games') games.save() joysticks = Category(title="Joysticks", parent=games, slug='joysticks') joysticks.save() tv = Category(title="TV", parent=entertainment, slug='tv') tv.save() mobile = Category(title="Mobile", slug='mobile') mobile.save() smartphones = Category(title="Smartphones", parent=mobile, slug='smartphones') smartphones.save() tablets = Category(title="Tablets", parent=mobile, slug='tablets') tablets.save()
def db_init(): """ setUp Test """ user = User.objects.create(email='*****@*****.**') user.set_password('@unMotdePasse') user.save() data = Category(name="Sauce") data.save() data = Level(name="High") data.save() data = Product(name="Mayonnaise", url="https://mayo.fr", nutriscore="c", category_id=Category.objects.get(name="Sauce"), photo="https://mayo.fr/photo.jpg", salt_100g="1.00", sugars_100g="2.00", fat_100g="3.00", saturate_fat_100g="4.00", level_salt=Level.objects.get(name="High"), level_sugars=Level.objects.get(name="High"), level_saturate_fat=Level.objects.get(name="High"), level_fat=Level.objects.get(name="High"), code="100200300", last_modified_t="1568887200") data.save() data = Product(name="Sauce tomate", url="https://Sauce-tomate.fr", nutriscore="b", category_id=Category.objects.get(name="Sauce"), photo="https://Sauce-tomate.fr/photo.jpg", salt_100g="1.00", sugars_100g="2.00", fat_100g="3.00", saturate_fat_100g="4.00", level_salt=Level.objects.get(name="High"), level_sugars=Level.objects.get(name="High"), level_saturate_fat=Level.objects.get(name="High"), level_fat=Level.objects.get(name="High"), code="101201301", last_modified_t="10120130111") data.save() data = Product(name="Ketchup", url="https://Ketchup.fr", nutriscore="c", category_id=Category.objects.get(name="Sauce"), photo="https://Ketchup.fr/photo.jpg", salt_100g="1.00", sugars_100g="2.00", fat_100g="3.00", saturate_fat_100g="4.00", level_salt=Level.objects.get(name="High"), level_sugars=Level.objects.get(name="High"), level_saturate_fat=Level.objects.get(name="High"), level_fat=Level.objects.get(name="High"), code="102202302", last_modified_t="1768894400") data.save()