def add_categories(apps, schema_editor): for main_category in categories: mc = Category(name=main_category) mc.save() for subcategory in categories[main_category]: sc = Category(parent=mc, name=subcategory) sc.save()
def handle(self, *args, **options): self.stdout.write("Preparing seed data...") if not User.objects.filter(username="******").exists(): instaman = User.objects.create_user("instaman", password="******") instaman.save() self.stdout.write("Creating instaman user...") else: self.stdout.write( "Username instaman already exists, skipping to seed data...") if not Category.objects.filter(category_name="Food").exists(): food_category = Category( user_id=User.objects.get(username="******"), category_name="Food") food_category.save() food_hashtags = ["Keto", "Low Fat", "Healthy", "Power", "Munchies"] for hashtag_item in food_hashtags: if not Hashtag.objects.filter( category_id=Category.objects.get(category_name="Food"), hashtag=hashtag_item).exists(): hashtag_create = Hashtag( category_id=Category.objects.get(category_name="Food"), hashtag=hashtag_item) hashtag_create.save() self.stdout.write("Creating " + hashtag_item + " hashtag") if not Category.objects.filter(category_name="Gym").exists(): gym_category = Category( user_id=User.objects.get(username="******"), category_name="Gym") gym_category.save() gym_hashtags = ["Workout", "Fitness", "Health", "Strong", "Muscles"] for hashtag_item in gym_hashtags: if not Hashtag.objects.filter( category_id=Category.objects.get(category_name="Gym"), hashtag=hashtag_item).exists(): hashtag_create = Hashtag( category_id=Category.objects.get(category_name="Gym"), hashtag=hashtag_item) hashtag_create.save() self.stdout.write("Creating " + hashtag_item + " hashtag") if not Category.objects.filter(category_name="Living").exists(): living_category = Category( user_id=User.objects.get(username="******"), category_name="Living") living_category.save() living_hashtags = ["Life", "Live Long", "Run", "Strong", "Mind"] for hashtag_item in living_hashtags: if not Hashtag.objects.filter( category_id=Category.objects.get(category_name="Living"), hashtag=hashtag_item).exists(): hashtag_create = Hashtag( category_id=Category.objects.get(category_name="Living"), hashtag=hashtag_item) hashtag_create.save() self.stdout.write("Creating " + hashtag_item + " hashtag") self.stdout.write("All data seeded...")
def setUp(self): '''Set up the test and category infrastructure.''' #Course Instantiation self.course = Course(name="testing course", slug="testing-course") self.course.save() self.course2 = Course(name="testing course2", slug="testing-course2") self.course2.save() #Course Section Instantiation self.coursesection = CourseSection(name="Section 1", course=self.course) self.coursesection.save() self.coursesection2 = CourseSection(name="Section 2", course=self.course2) self.coursesection2.save() #Category Instantiation self.category = Category( name="Category 1 for testing course", slug="cat-1-testing-course", section=self.coursesection, ) self.category.save() self.category2 = Category( name="Category 1 for testing course", slug="cat-1-testing-course2", section=self.coursesection2, ) self.category2.save() #SubCategory Instantiation self.subcategory = SubCategory( name="SubCategory 1 for testing course", slug="subcategory-1-testing-course", category=self.category, ) self.subcategory.save() self.subcategory2 = SubCategory( name="SubCategory 2 for testing course", slug="subcategory-2-testing-course", category=self.category2, ) self.subcategory2.save() #User creation self.user = MyUser.objects.create_test_user( username="******", email="*****@*****.**", password="******", )
def form_valid(self, form): username = form.cleaned_data['username'] password1 = form.cleaned_data['password1'] password2 = form.cleaned_data['password2'] email = form.cleaned_data['email'] user=form.save() initial_balance_category = Category(user = user, master_category='Initial Balance', category='Initial Balance') initial_balance_category.save() income_category = Category (user = user, master_category = 'Income', category = 'Income' ) income_category.save() return super().form_valid(form)
def category_create(request, name, author): if request.method == 'POST': user = User.objects.get(username=author) category = Category(name=name, author=user) category.save() return {"result": "success"} return {"error": "not post"}
def setUp(self): # Create User and Token self.user = User.objects.create_user('*****@*****.**', '123456test') self.user.first_name = 'Helpinghand' self.user.last_name = 'Apps' self.user.save() self.token = Token.objects.create(user=self.user) # Token Authentication self.api_authentication() # Test date self.date = datetime.datetime.utcnow() + datetime.timedelta(minutes=5) # Create Category self.category = Category(name='Clothing') self.category.save() # Create Need self.title = 'Need shoes' self.is_fixed = True self.description = 'In need of shoes for my son.' self.address = 'Prins Bernhardstraat 13' self.need = Need(title=self.title, description=self.description, address=self.address, end_date=self.date, is_fixed=self.is_fixed, creator=self.user, ) self.need.save() self.need.categories.add(self.category) self.need.supporters.add(self.user)
def create(request): if request.method == 'POST': # POST, generate form with data from the request form = CategoryForm(request.POST, request.FILES) # check if it's valid: if form.is_valid(): # emailAddress = form.cleaned_data['email'] # process data, insert into DB, generate email,etc # redirect to a new url: for field in request.FILES.keys(): for formfile in request.FILES.getlist(field): save_uploaded_file_to_media_root(formfile) # Create a model Category instance category = Category(categoryName=form.cleaned_data['categoryName']) # Invoke the save() method to create/save the record # No record id reference, so a create operation is made and the reference is updated with id category.save() # Invoke the save() method to update/save the record # Record has id reference from prior save() call, so operation is update # store_corporate.save() return HttpResponseRedirect('/categories/index') else: pass else: # GET, generate blank form request.user.first_name = "zubair" request.user.email = "*****@*****.**" form = CategoryForm() return render(request, 'categories/create.html', {'form': form})
def mutate(self, info, name): user = info.context.user # Validate user is admin validate_user_is_admin(user) # Sanitize inputs validate_name(name) validate_name_unique(name) # Save the category category = Category(name=name) category.save() # Push the realtime data to rethinkdb connection = r.connect(host=RDB_HOST, port=RDB_PORT) try: r.db(CTF_DB).table('categories').insert({ 'sid': category.id, 'name': category.name, 'created': format(category.created, 'U') }).run(connection) except RqlRuntimeError as e: raise Exception('Error adding category to realtime database: %s' % (e)) finally: connection.close() return AddCategory(status='Category Created')
def handle(self, *args, **options): number_to_create: int = options['categories'] fake: Generator = Factory.create( getattr(settings, 'FAKER_LOCALE', None)) categories: QuerySet = Category.objects.all() assert categories.exists() == True, 'At least one root category should exist.' existing_names = set(categories.values_list('name', flat=True)) new_names = [] while number_to_create > 0: name = fake.street_name() if name not in existing_names: new_names.append(name) existing_names.add(name) number_to_create -= 1 for new_name in tqdm(new_names, desc='Creating new categories'): parent: Category = random.choice(categories) new_category: Category = Category( name=new_name, description=fake.paragraph(), is_closed=random.choices( [True, False], weights=[0.1, 0.9])[0], require_threads_approval=random.choices( [True, False], weights=[0.1, 0.9])[0], require_posts_approval=random.choices( [True, False], weights=[0.1, 0.9])[0] ) new_category.insert_at(parent, position='last-child', save=True) # Refresh categories from database categories = categories.all()
def index(request): if not auth.is_super(request): return redirect('login') categories = Category.objects.all() if request.method == "POST": if (request.POST['name'] == ''): msg = 'You must insert category name!' alert = 'danger' else: category = Category(name=request.POST['name']) try: category.save() msg = 'New category added successfully' alert = 'success' except IntegrityError as e: msg = 'Category already added!' alert = 'danger' return render(request, 'all.html', { "categories": categories, "msg": msg, "alert": alert }) else: return render(request, 'all.html', {"categories": categories})
def test_serialize(self): category = Category(name='test_serialize') expected = {'id': 1, 'name': 'test_serialize'} category.save() result = CategorySerializer(category).data self.assertEqual(expected, result)
def test_get_category(self): m = mock.Mock() m.get.return_value = Category(name="Winter") categoryManager = CategoryManager(m) category = categoryManager.get_category_by_name(1) self.assertEquals(category.name, "Winter")
def _collect_categories(self, channel, file): with open(file, 'r') as f: rows = reader(f) root = Category(title='Category', channel=channel) nodes = [root] parents = [nodes[0]] """ The existence of '/' is verified at each iteration in a row. If it does not exist, the root node is considered as the parent node of the node to be added, otherwise the previous node is fetched from parents and added as the parent node of the node to be added. Obs: parents is updated with each Category.add_nodes () call """ for row in rows: if row and '/' not in row[0] and row[0] != 'Category': node = Category(title=row[0].strip(), parent=parents[0], channel=channel) nodes.append(node) nodes = Category.add_node(nodes=nodes) self._print_green("Category: %s added" % nodes[-1].title) elif row and '/' in row[0]: parts = [p for p in row[0].split('/')] size_parts = len(parts) if size_parts > 2: """ The loop begins at the end. The probability that a parent node is at the other end of the list is larger and makes the search less costly. """ parent = [i for i in nodes[::-1] if i.title == parts[:-1][-1].strip() and i.parent.title == parts[:-1][-2].strip()][0] elif size_parts >= 2: parent = [i for i in nodes[::-1] if i.title == parts[:-1][-1].strip() and i.parent == root][0] else: parent = nodes[0] node = Category(title=parts[-1].strip(), parent=parent, channel=channel) nodes.append(node) nodes = Category.add_node(nodes=nodes) self._print_green("Category: %s added" % nodes[-1].title) return nodes
def depth_first_create_category(tree, parent=None) -> Iterable[Category]: cat = Category(name=tree['name'], parent=parent) create_child = partial(depth_first_create_category, parent=cat) children = map(create_child, tree.get('children', ())) yield cat for c in children: yield from c
def test_save_category(self): category = Category(name="Winter") m = mock.Mock() m.save.return_value = 1 categoryManager = CategoryManager(m) id_last_category = categoryManager.save_category(category) self.assertEquals(id_last_category, 1)
def setUp(self): '''Set up the test and category infrastructure.''' #Course Instantiation self.course = Course(name="testing course", slug="testing-course") self.course.save() #Course Section Instantiation self.coursesection = CourseSection(name="Section 1", course=self.course) self.coursesection.save() #Category Instantiation self.category = Category( name="Category 1 for testing course", slug="cat-1-testing-course", section=self.coursesection, ) self.category.save() #SubCategory Instantiation self.subcategory = SubCategory( name="SubCategory 1 for testing course", slug="subcategory-1-testing-course", category=self.category, ) self.subcategory.save() #User creation self.user = MyUser.objects.create_test_user( username="******", email="*****@*****.**", password="******", ) self.user2 = MyUser.objects.create_test_user( username="******", email="*****@*****.**", password="******", ) #Question creation self.question = Question( course=self.course, section=self.coursesection, category=self.category, subcategory=self.subcategory, question_text="Here is an example question.", option_A="Here is option A.", option_B="Here is option B.", answer_letter="A", answer_explanation="Here is an example explanation.", index=1, ) self.question.save()
def get_other_category(self, category): if self._other_category_cache: return self._other_category_cache try: self._other_category_cache = Category.objects.get(name=category) return self._other_category_cache except Category.DoesNotExist: category = Category(name=category, slug=slugify(category)) category.save() self._other_category_cache = category return self._other_category_cache
def test_except_name_conflict_in_create(self): category_name = 'test1' Category(name=category_name).save() data = json.dumps({'name': category_name}) # Interesting fact that DRF.APIRequestFactory # overwrite `_encode_data` method of DjangoRequestFactory # and if `content_type` provided (which provided always by default == multipart) # it will encode all passed `data` to bytestring. # It is completely fails Liskov Substitution principle. Nice! resp = self.client.post('/categories/', data=data, content_type='application/json') self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST) self.assertTrue(category_name in resp.json()['error'])
def make_category(self, string, parent=None, order=1): """ Make and save a category object from a string """ cat = Category( name=string.strip(), slug=slugify(SLUG_TRANSLITERATOR(string.strip()))[:49], #parent=parent, order=order) cat._tree_manager.insert_node(cat, parent, 'last-child', True) cat.save() if parent: parent.rght = cat.rght + 1 parent.save() return cat
def setUp(self): self.c = Client() self.student = User.objects.create(username="******", email="*****@*****.**") self.student.set_password( "amadeus") #because of the hash function used self.student.save() if self.c.login(email="*****@*****.**", password="******"): print("student01 logged in") self.student02 = User.objects.create(username="******", email="*****@*****.**") self.student02.set_password("amadeus") self.student02.save() self.category = Category(name="category 01") self.category.save()
def save_cat_heirarchy(self, category, parent): #print category['display_name'],parent['display_name'] if parent else None cat = Category() cat.name = category['display_name'] cat.ext_id = category['category_id'] cat.slug = slugify(cat.name) client = Client.objects.get(id=3) cat.client = client cat.save() cat_graph = CategoryGraph() cat_graph.category = cat if parent: parent = Category.objects.get(name=parent['display_name'], client=client) cat_graph.parent = parent cat_graph.save()
def setUp(self): self.category = Category(name="Test cat") self.category.save_category() self.location = Location(name="Test Loc") self.location.save_location() self.image = Image( name="Test Img", location_id=self.location, category_id=self.category, image=SimpleUploadedFile( name='image_test.jpg', content=open( 'photo_gallery/static/images/default_location.jpg', 'rb').read(), content_type='image/jpeg'))
def test_get_detailed_artifact_page(self): category = Category( category_name="Test Category", category_description="Test Category", ) category.save() artifact = Artifact( name="Test", reserve_price="1.11", purchase_price="1.11", quantity=1, category=category, ) artifact.save() page = self.client.get("/artifacts/view/{0}".format(artifact.id)) self.assertEqual(page.status_code, 200) self.assertTemplateUsed(page, "artifact_detail.html")
def create_category(): if current_user.is_not_admin(): return jsonify( get_error_response('Permission denied, you must be admin', status_code=401)) name = request.form.get('name') description = request.form.get('description') category = Category(name=name, description=description) if 'images[]' in request.files: for image in request.files.getlist('images[]'): if image and validate_file_upload(image.filename): filename = secure_filename(image.filename) dir_path = app.config['IMAGES_LOCATION'] dir_path = os.path.join((os.path.join(dir_path, 'categories'))) if not os.path.exists(dir_path): os.makedirs(dir_path) file_path = os.path.join(dir_path, filename) image.save(file_path) file_path = file_path.replace( app.config['IMAGES_LOCATION'].rsplit(os.sep, 2)[0], '') if image.content_length == 0: file_size = image.content_length else: file_size = os.stat(file_path).st_size ci = CategoryImage(file_path=file_path, file_name=filename, original_name=image.filename, file_size=file_size) category.images.append(ci) db.session.add(category) db.session.commit() return get_success_response(data=category.get_summary(), messages='Category created successfully')
def save_cat_heirarchy(self,category,parent): client = Client.objects.get(name='bigbazaar') try: cat = Category.objects.get(ext_id=category['category_id'],client=client) except Category.DoesNotExist: cat = Category() cat.name = category['display_name'] cat.ext_id = category['category_id'] cat.slug = slugify(cat.name) cat.client = client cat.save() if parent: parent = Category.objects.get(ext_id=parent['category_id'],client=client) try: cat_graph = CategoryGraph.objects.get(category=cat,parent=parent) except CategoryGraph.DoesNotExist: cat_graph = CategoryGraph() cat_graph.category = cat cat_graph.parent = parent cat_graph.save()
def post(self, request, *args, **kwargs): restaurant = Restaurant(owner=self.request.user, name=request.data['name'], country=request.data['country'], street=request.data['street'], city=request.data['city'], phone=request.data['phone']) restaurant.save() if request.data['category']: result = Category.objects.filter( name__icontains=request.data['category']) if result: for category in result: restaurant.m2m_restaurant_cat.add(category) else: category = Category(name=request.data['category']) category.save() restaurant.m2m_restaurant_cat.add(category) return Response(status=200)
def get_or_create_category_mapping(account, theirs, ours, store=None): if not ours: ours = "Uncategorized" try: c = Category.objects.using('default').get(name=ours) except Category.DoesNotExist: # create category if it does not exist c = Category(name=ours, slug=slugify(ours)) if store: c.store = Store.objects.using('default').get(name=store) c.moderate = True c.save(using='default') try: category_mapping = CategoryMapping.objects.using('default').get( category=theirs, account=account, mapped_to=c) return category_mapping except CategoryMapping.DoesNotExist: category_mapping = CategoryMapping(category=theirs, account=account, mapped_to=c) category_mapping.save(using='default') return category_mapping
def handle(self, *args, **options): for e in range(5): name = CATEGORIES[e] img = 'https://s3.amazonaws.com/bartering-images/categories/' + str(e+1) + '.jpg' category = Category(name=name, img=img) category.save() print('categories created successfully!') for u in range(20): first_name = random.choice(FIRST_NAMES) last_name = random.choice(LAST_NAMES) username = first_name.lower() + last_name.lower() + str(u) email = username + '@mail.com' age = random.randint(18, 80) phone = random.randint(10000000, 99999999) img = 'https://s3.amazonaws.com/bartering-images/users/' + \ str(random.randint(0, 7)) + '.jpg' new_user = User(first_name=first_name, last_name=last_name, username=username, password=PASSWORD, email=email, age=age, phone=phone, rating=RATING, img=img) new_user.set_password(PASSWORD) new_user.save() print('users created successfully!') for b in range(30): name = random.choice(BELONGING_NAMES) category = Category.objects.get(pk=random.randint(1, 5)) description = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' state = random.randint(0,5); belongs_to = User.objects.get(pk=random.randint(1, 20)) img = 'https://s3.amazonaws.com/bartering-images/belongings/' + \ str(BELONGING_NAMES.index(name)) + '.jpg' new_belonging = Belonging( name=name, category=category, description=description, state=state, belongs_to=belongs_to, img=img) new_belonging.save() print('belongings created successfully!') for u in range(40): offered_item = Belonging.objects.get(pk=random.randint(1, 30)) title = random.choice(POST_ACTIONS) + ' ' + offered_item.name posted_by = User.objects.get(pk=random.randint(1, 20)) description = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' category = offered_item.category img = offered_item.img new_post = Post(title=title, offered_item=offered_item, posted_by=posted_by, description=description, category=category, img=img) new_post.save() print('posts created successfully!') for o in range(50): offered_by = User.objects.get(pk=random.randint(1, 20)) offered_in = Post.objects.get(pk=random.randint(1, 40)) new_offer = Offer(offered_by=offered_by, offered_in=offered_in) new_offer.save() print('offers created successfully!') for a in range(150): offer = Offer.objects.get(pk=random.randint(1,50)) belongin = Belonging.objects.get(pk=random.randint(1,30)) new_BelonginsPerOffer = BelongingsPerOffer(offer=offer, belonging=belongin) new_BelonginsPerOffer.save() print('objetsInOffer created successfully!') print('Fake data created successfully!')
def insertCategories(): # Save the category web = Category(name="Web") web.save() rookie = Category(name="Rookie") rookie.save() programming = Category(name="Programming") programming.save() crypto = Category(name="Crypto & Puzzles") crypto.save() advanced = Category(name="Advanced") advanced.save() data = Category(name="Data") data.save() bonus = Category(name="_Bonus") bonus.save() # Push test categories to rethinkdb database connection = r.connect(host=RDB_HOST, port=RDB_PORT) try: r.db(CTF_DB).table('categories').insert({ 'sid': web.id, 'name': web.name, 'created': format(web.created, 'U') }).run(connection) r.db(CTF_DB).table('categories').insert({ 'sid': rookie.id, 'name': rookie.name, 'created': format(rookie.created, 'U') }).run(connection) r.db(CTF_DB).table('categories').insert({ 'sid': programming.id, 'name': programming.name, 'created': format(programming.created, 'U') }).run(connection) r.db(CTF_DB).table('categories').insert({ 'sid': crypto.id, 'name': crypto.name, 'created': format(crypto.created, 'U') }).run(connection) r.db(CTF_DB).table('categories').insert({ 'sid': advanced.id, 'name': advanced.name, 'created': format(advanced.created, 'U') }).run(connection) r.db(CTF_DB).table('categories').insert({ 'sid': data.id, 'name': data.name, 'created': format(data.created, 'U') }).run(connection) r.db(CTF_DB).table('categories').insert({ 'sid': bonus.id, 'name': bonus.name, 'created': format(bonus.created, 'U') }).run(connection) except RqlRuntimeError as e: raise Exception('Error adding categories to realtime database: %s' % (e)) finally: connection.close()
if data.get('event'): print(data.get('event')) event = Event(name=data['event']['name'], private=data['event']['privacy'], start=data['event']['time']['start'], end=data['event']['time']['end']) event.save() if data.get('setting'): cap = Capacity(capacity=data['setting']['team']['capacity']) cap.save() for cat in data['board']['categories']: print(cat['name']) ca = Category(name=cat['name'], description=cat['description']) ca.save() ''' Challenge create. Required: Category, Name, Description, Points, Flag ''' for challenge in cat['challenges']: print(" |--", challenge['name']) if challenge['name'] and challenge['description'] and challenge[ 'points'] and challenge['flag']: chal = Challenge(category=ca, name=challenge['name'], description=challenge['description'], points=challenge['points'], hidden=False)