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 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 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 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 get(request: HttpRequest): pk = request.GET.get('id') category = get_object_or_404(Category, pk=pk) category_serialized = {'id': category.pk, 'name': category.name} parents_serialized = [{ 'id': parent.id, 'name': parent.name } for parent in Category.get_parents(pk)] children_serialized = [{ 'id': child.id, 'name': child.name } for child in Category.get_children(pk)] siblings_serialized = [{ 'id': sibling.id, 'name': sibling.name } for sibling in Category.get_siblings(pk)] result = category_serialized result.update({'parents': parents_serialized}) result.update({'children': children_serialized}) result.update({'sibling': siblings_serialized}) return JsonResponse(result)
class NotificationTests(TestCase): '''Tests related to the actual Notification functionality.''' def setUp(self): '''Set up the user infrastructure.''' #User creation self.user = MyUser.objects.create_test_user( username="******", email="*****@*****.**", password="******", ) #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() 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.", ) self.question.save() def test_notification_creation(self): '''Test the creation of a notification.''' notification = Notification.objects.create( text="Notification test", recipient=self.user, link=self.question.get_absolute_url()) notification.read = True notification.save()
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 test_serialize(self): category = Category(name='test_serialize') expected = {'id': 1, 'name': 'test_serialize'} category.save() result = CategorySerializer(category).data self.assertEqual(expected, result)
class TestImage(TestCase): 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_save_image(self): self.image.save_image() images = Image.objects.all() self.assertTrue(len(images) > 0) def test_object_instance(self): self.image.save_image() images = Image.objects.all() self.assertIsInstance(images[0], Image) def test_del_image(self): self.image.save_image() self.image.delete_image() images = Image.objects.all() self.assertTrue(len(images) == 0) def test_updated_image(self): self.image.save_image() data = dict(name="New Name") self.image.update_image(self.image.id, data) self.assertTrue(self.image.name, "New Name") def test_get_img_by_id(self): self.image.save_image() print(self.image) res = self.image.get_image_by_id(image_id=self.image.id) self.assertIsInstance(res, Image) def test_filter_img_by_loc(self): self.image.save_image() res = self.image.filter_by_location(location_id=self.location.id) self.assertTrue(len(res), 1) self.assertEqual(res[0].location_id.name, self.location.name) def test_search_image(self): self.image.save_image() res = self.image.search_image(category_id=self.category.id) self.assertTrue(len(res), 1) self.assertEqual(res[0].category_id.name, self.category.name)
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 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 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 _initial_handle(self, channel_name, file_name): """ The channel and file parameters match the channel name and file, the file must be in the same directory as the manage.py file """ if self._validate_format_file(file_name): base_file = self._mount_path_file(file_name) channel = self._create_channel(channel_name) nodes = self._collect_categories(channel, base_file) Category.persist_nodes(nodes) else: raise TypeError('Invalid File format')
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 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 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 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 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 test_get_list_view(self): response = self.client.get(reverse('categories:list')) self.assertEqual(response.status_code, 200) self.assertIn('categories', response.context) categories = list(response.context['categories']) all_categories = Category.all() self.assertTrue(all(category in all_categories for category in categories))
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 _update_parent(self, parent): if self.instance.get_parent() == parent: return if parent is None: # transform this on a root node self.instance.move(Category.get_first_root_node(), pos='sorted-sibling') else: self.instance.move(parent, pos='sorted-child')
def __init__(self): try: self.category = Category.objects.get(slug=self.category_slug) except Category.DoesNotExist: log.debug('Create category %s', self.category_slug) self.category = Category() name = self.category_slug.replace('-', ' ').capitalize() self.category.name = self.category.alternate_title = name self.category.save() for ext in ('jpg', 'png'): filename = os.path.join(settings.PROJECT_PATH, 'static', 'auto_categories', '%s.%s' % (self.category_slug, ext)) if os.path.exists(filename): break if not bool(self.category.thumbnail): if os.path.exists(filename): file_content = ContentFile(open(filename).read()) self.category.thumbnail.save(os.path.basename(filename), file_content) log.debug('Using %s as thumbnail', filename) else: log.warn( 'Category "%s" do not have an image declared. We expect %s', self.category, filename)
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 _create_node(self, parent): keys = ['name', 'description', 'slug'] data = {} for key in keys: data[key] = self.cleaned_data[key] if parent is None: # reate a root node root = Category.get_first_root_node() if root: self.instance = root.add_sibling(pos='sorted-sibling', **data) else: self.instance = Category.add_root(**data) else: child = parent.get_first_child() if child: self.instance = child.add_sibling(pos='sorted-sibling', **data) else: self.instance = parent.add_child(**data)
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 _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 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 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 init(): """ Adds all root nodes first, then recursively iterates through the children and assigns the nodes accordingly. """ root = Category.add_root(name="Amazon Categories", node_id=0) for root_category, root_id in root_categories: print root_category parent = root.add_child(name=root_category, node_id=root_id) result = api.browse_node_lookup(root_id) set_children(parent, result)
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 create(self, validated_data): str_ids = self.context['request'].data[ 'categories'] #this is to have the data in case of many to many because many to many needs 2 instances and the validated data dosen send the infos of many to many. ids = json.loads(str_ids) new_product = super().create( validated_data ) # it will return instance with empty categories because its many to many field and its null=True by default categories = Category.get_categories_by_ids(ids) for cat in categories: new_product.categories.add(cat) return new_product
def atomicEmployeeAndOrder(request): if request.POST.get("atomic", ""): region = Region(pk = 5, regiondescription = "Polska"); region.save(); category = Category(categoryname="computers", description="super"); category.save(); if request.POST.get("savepoints", ""): region = Region(pk = 5, regiondescription = "Polska"); region.save() try: spoint = transaction.savepoint() category = Category(categoryname="computers", description="super") category.save(); raise Exception("I know python!") transaction.savepoint_commit(spoint) except Exception: transaction.savepoint_rollback(spoint) return render_to_response("atomic.html", locals(), context_instance=RequestContext(request))
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 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 category_list(request, format=None): """List all code categories, or create a new category.""" if request.method == 'GET': categories = Category.get_active() serializer = CategorySerializer(categories, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = CategorySerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
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 new_category(request, cat_id): if cat_id == 'root': parent_cat = None else: try: parent_cat = Category.objects.get(pk=int(cat_id)) except (ValueError, ObjectDoesNotExist): messages.error(request, 'Please choose a valid parent category.') return redirect('categories') name = request.POST.get('category_name') if not name: messages.error(request, 'Please choose a category name.') return redirect('categories') category = Category( user=request.user, parent=parent_cat, name=request.POST.get('category_name'), description=request.POST.get('category_desc'), ) category.full_clean() category.save() messages.success(request, 'Created new category.') return redirect('categories')
def CategorizeUnknown(category_str): """ Internal function for adding categories that aren't already listed in the initial NTEE category population. This function is called when a category is found on the Guidestar database that doesn't already exist. """ category_str = str(category_str) # safety dance try: cat = Category.objects.get(name=category_str) print 'Found NTEE category already in database.' except Category.DoesNotExist: try: cat = Category.objects.get(meta_keywords=category_str.split()[0]) print 'Found NTEE Code already in database.' except Category.DoesNotExist: try: cat = Category(name=category_str, meta_keywords=category_str.split()[0]) cat.alternate_title = cat.name.split()[0] cat.parent = Category.objects.get(meta_keywords=category_str.split()[0][0]) cat.save() except: print 'Error trying to categorize unknown.'
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 add_company(request): form1 = UserProfileForm(request.POST) form2 = UserCreateForm(request.POST) form3 = CompanyForm(request.POST) if form1.is_valid() and form2.is_valid() and form3.is_valid(): up = form1.save(commit=False) c = form3.save() c.active = True c.favorite = True c.save() u = form2.save() up.user = u up.save() up.companies.add(c) for user in User.objects.filter(is_superuser=True): user.userprofile.companies.add(c) user.userprofile.save() # add dossier global fy_init = FiscalYear.objects.filter(init=True)[0] y_init = Year(fiscal_year=fy_init, active=True, refer_company=c, favorite=False) y_init.save() c.years.add(y_init) tt_init = TemplateTrimester.objects.filter(year=fy_init, favorite=True)[0] tri_init = Trimester(template=tt_init, start_date=tt_init.start_date, active=True, refer_year=y_init, favorite=True) tri_init.save() y_init.trimesters.add(tri_init) tp_init = TypeCategory.objects.filter(priority=10)[0] cat_init = Category(cat=tp_init, refer_trimester=tri_init, active=True) cat_init.save() tri_init.categories.add(cat_init) # add favorite_year and favorite_trimester fy_fav = FiscalYear.objects.filter(favorite=True)[0] y_fav = Year(fiscal_year=fy_fav, active=True, refer_company=c, favorite=True) y_fav.save() c.years.add(y_fav) tt_fav = TemplateTrimester.objects.filter(year=fy_fav, favorite=True)[0] tri_fav = Trimester(template=tt_fav, start_date=tt_fav.start_date, active=True, refer_year=y_fav, favorite=True) tri_fav.save() y_fav.trimesters.add(tri_fav) for tp in TypeCategory.objects.filter(priority__lt=10).order_by('priority'): cat_fav = Category(cat=tp, refer_trimester=tri_fav, active=True) cat_fav.save() tri_fav.categories.add(cat_fav) c = {'return': True, 'list': Company.objects.all(), 'form': [UserProfileForm(), UserCreateForm(), CompanyForm()], 'url': '/company/add/'} return render(request, 'list.tpl', c) else: c = {'view_form': True, 'list': Company.objects.all(), 'form': [form1(), form2(), form3()]} return render(request, 'list.tpl', c)
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 __init__(self): try: self.category = Category.objects.get(slug=self.category_slug) except Category.DoesNotExist: log.debug("Create category %s", self.category_slug) self.category = Category() self.category.name = self.category_name self.category.description = self.category_description self.category.save() for ext in ("jpg", "png"): filename = os.path.join( settings.PROJECT_DIR, "static", "auto_categories", "%s.%s" % (self.category_slug, ext) ) if os.path.exists(filename): break if not bool(self.category.thumbnail): if os.path.exists(filename): file_content = ContentFile(open(filename).read()) self.category.thumbnail.save(os.path.basename(filename), file_content) log.debug("Using %s as thumbnail", filename) else: log.warn('Category "%s" do not have an image declared. We expect %s', self.category, filename)
def add_categories(self): for c in TypeCategory.objects.filter(active=True, default=True).order_by("priority"): new_cat = Category(cat=c, refer_trimester=self) new_cat.save() self.categories.add(new_cat)
def CategoryPopulate(): """ Internal Function to populate the database with the initial Category information from the National Taxonomy of Tax Exempt Organizations (NTEE) """ if ON_OPENSHIFT: lines = open(os.path.join(os.environ['OPENSHIFT_DATA_DIR'], 'npo', 'ntee-categories.txt'), 'r').readlines() else: lines = open('npo/ntee-categories.txt', 'r').readlines() for line in lines: if line != '': try: # Clean lines and write them to database category = Category.objects.get(name=line.strip()) print 'Category', category, 'already exists.' except Category.DoesNotExist: category = Category(name=line.strip(), meta_keywords=line.split()[0]) print 'Writing Category %s to database...' % line.strip() # NTEE Code set as first meta keyword for each category category.meta_keywords = category.name.split()[0] category.alternate_title = category.name.split()[0] category.save() ### Assign Parent Categories if line.startswith('A') and line[1] != ' ': # A is the parent Category category.parent = Category.objects.get(name='A Arts, Culture, and Humanities') if line.startswith('B') and line[1] != ' ': # B is the parent Category category.parent = Category.objects.get(name='B Educational Institutions') if line.startswith('C') and line[1] != ' ': # C is the parent Category category.parent = Category.objects.get(name='C Environmental Quality Protection, Beautification') if line.startswith('D') and line[1] != ' ': # D is the parent Category category.parent = Category.objects.get(name='D Animal related') if line.startswith('E') and line[1] != ' ': # E is the parent Category category.parent = Category.objects.get(name='E Health—General & Rehabilitative') if line.startswith('F') and line[1] != ' ': # F is the parent Category category.parent = Category.objects.get(name='F Mental Health, Crisis Intervention') if line.startswith('G') and line[1] != ' ': # G is the parent Category category.parent = Category.objects.get(name='G Disease, Disorders, Medical Disciplines') if line.startswith('H') and line[1] != ' ': # H is the parent Category category.parent = Category.objects.get(name='H Medical Research') if line.startswith('I') and line[1] != ' ': # I is the parent Category category.parent = Category.objects.get(name='I Crime, Legal Related') if line.startswith('J') and line[1] != ' ': # J is the parent Category category.parent = Category.objects.get(name='J Employment, Job Related') if line.startswith('K') and line[1] != ' ': # K is the parent Category category.parent = Category.objects.get(name='K Agriculture, Food, Nutrition') if line.startswith('L') and line[1] != ' ': # L is the parent Category category.parent = Category.objects.get(name='L Housing, Shelter') if line.startswith('M') and line[1] != ' ': # M is the parent Category category.parent = Category.objects.get(name='M Public Safety, Disaster Preparedness and Relief') if line.startswith('N') and line[1] != ' ': # N is the parent Category category.parent = Category.objects.get(name='N Recreation, Sports, Leisure, Athletics') if line.startswith('O') and line[1] != ' ': # O is the parent Category category.parent = Category.objects.get(name='O Youth Development') if line.startswith('P') and line[1] != ' ': # P is the parent Category category.parent = Category.objects.get(name='P Human Services') if line.startswith('Q') and line[1] != ' ': # Q is the parent Category category.parent = Category.objects.get(name='Q International, Foreign Affairs, and National Security') if line.startswith('R') and line[1] != ' ': # R is the parent Category category.parent = Category.objects.get(name='R Civil Rights, Social Action, Advocacy') if line.startswith('S') and line[1] != ' ': # S is the parent Category category.parent = Category.objects.get(name='S Community Improvement, Capacity Building') if line.startswith('T') and line[1] != ' ': # T is the parent Category category.parent = Category.objects.get(name='T Philanthropy, Voluntarism, and Grantmaking') if line.startswith('U') and line[1] != ' ': # U is the parent Category category.parent = Category.objects.get(name='U Science and Technology Research Institutes') if line.startswith('V') and line[1] != ' ': # V is the parent Category category.parent = Category.objects.get(name='V Social Science Research Institutes') if line.startswith('W') and line[1] != ' ': # W is the parent Category category.parent = Category.objects.get(name='W Public, Society Benefit') if line.startswith('X') and line[1] != ' ': # X is the parent Category category.parent = Category.objects.get(name='X Religion, Spiritual Development') if line.startswith('Y') and line[1] != ' ': # Y is the parent Category category.parent = Category.objects.get(name='Y Mutual/Membership Benefit Organizations, Other') if line.startswith('Z') and line[1] != ' ': # Z is the parent Category category.parent = Category.objects.get(name='Z Unknown') category.save()
def create_test_category(): category = Category(name="Test category") category.save() return category
class Base(object): """Base task. Define hooks and a __task__ to retrieve tasks. subclasses must override process_entry() and may call add_category() """ __task__ = True queryset = None category_name = None category_description = None def __init__(self): try: self.category = Category.objects.get(slug=self.category_slug) except Category.DoesNotExist: log.debug("Create category %s", self.category_slug) self.category = Category() self.category.name = self.category_name self.category.description = self.category_description self.category.save() for ext in ("jpg", "png"): filename = os.path.join( settings.PROJECT_DIR, "static", "auto_categories", "%s.%s" % (self.category_slug, ext) ) if os.path.exists(filename): break if not bool(self.category.thumbnail): if os.path.exists(filename): file_content = ContentFile(open(filename).read()) self.category.thumbnail.save(os.path.basename(filename), file_content) log.debug("Using %s as thumbnail", filename) else: log.warn('Category "%s" do not have an image declared. We expect %s', self.category, filename) def get_queryset(self): return self.queryset.all() def delete_existings(self): qs = self.category.representative_set.through.objects.filter(category=self.category).all() try: qs.delete() except: # qs is to large to be delete in one step for obj in qs: obj.delete() def add_category(self, entry): entry.achievements.add(self.category) entry.save() def process_entry(self, entry): self.add_category(entry) @property def category_slug(self): return slugify(self.category_name) def __call__(self): log.info("Delete existing %s", self.category) self.delete_existings() log.info("Processing %s", self.category) for entry in self.get_queryset(): try: self.process_entry(entry) except Exception, e: log.error("Error while processing %s for %s", self.category, entry) log.exception(e)
class APIDashBoardTest(TestCase): 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 test_most_used_tags(self): """ testing if the catches all tags used in a resource and in a subject """ t = Tag(name="felipe") t.save() t1 = Tag(name="b2") t1.save() s1 = Subject.objects.create(name="subject", visible= True, init_date= datetime.now(), end_date= datetime.now(), subscribe_begin = datetime.now(), subscribe_end= datetime.now() ) s1.tags.add(t) s1.save() s2 = Subject.objects.create(name="subject dois", visible= True, init_date= datetime.now(), end_date= datetime.now(), subscribe_begin = datetime.now(), subscribe_end= datetime.now() ) s2.tags.add(t) s2.save() r1 = Resource.objects.create(name="resource um") r1.tags.add(t1) r1.save() expected_data = [{'name': 'felipe', 'count': 2}, {'name':'b2', 'count': 1}] data = self.c.get('/analytics/most_used_tags/') self.assertEqual(data.status_code, 200 ) self.assertJSONEqual(str(data.content, encoding='UTF-8'), expected_data) @override_settings(STATICFILES_STORAGE = None) # added decorator def test_most_accessed_subjects(self): """ test if we collect the correct amount of access to a subject """ s1 = Subject.objects.create(name="subject", visible= True, init_date= datetime.now(), end_date= datetime.now(), subscribe_begin = datetime.now(), subscribe_end= datetime.now() ) s1.students.add(self.student) s1.students.add(self.student02) s1.category = self.category s1.save() response = self.c.get('/subjects/view/'+str(s1.slug)+'/') print(response) self.assertEqual(response.status_code, 200) self.c.logout() #logout student one if self.c.login(email="*****@*****.**", password="******"): print("student02 logged in") response = self.c.get('/subjects/view/'+str(s1.slug)+'/') self.assertEqual(response.status_code, 200) response = self.c.get('/analytics/most_accessed_subjects/') self.assertEqual(response.status_code, 200) expected_data = [{'name': s1.name, 'count': 2}] self.assertJSONEqual(str(response.content, encoding = 'UTF-8'), expected_data) def test_most_accessed_categories(self): self.fail("finish test on categories") def test_most_active_users(self): self.fail("finish the test")
def test_trycategoryname(self): user = get_user_model().objects.create( username='******', ) cat = Category(name='TestCategory', parent=None, user=user) self.assertEqual(cat.__str__(), 'TestCategory')
class Base(object): """Base task. Define hooks and a __task__ to retrieve tasks. subclasses must override process_entry() and may call add_category() """ __task__ = True queryset = None category_slug = None def __init__(self): try: self.category = Category.objects.get(slug=self.category_slug) except Category.DoesNotExist: log.debug('Create category %s', self.category_slug) self.category = Category() name = self.category_slug.replace('-', ' ').capitalize() self.category.name = self.category.alternate_title = name self.category.save() for ext in ('jpg', 'png'): filename = os.path.join(settings.PROJECT_PATH, 'static', 'auto_categories', '%s.%s' % (self.category_slug, ext)) if os.path.exists(filename): break if not bool(self.category.thumbnail): if os.path.exists(filename): file_content = ContentFile(open(filename).read()) self.category.thumbnail.save(os.path.basename(filename), file_content) log.debug('Using %s as thumbnail', filename) else: log.warn( 'Category "%s" do not have an image declared. We expect %s', self.category, filename) def get_queryset(self): return self.queryset.all() def delete_existings(self): qs = self.category.representative_set.through.objects.filter( category=self.category).all() try: qs.delete() except: # qs is to large to be delete in one step for obj in qs: obj.delete() def add_category(self, entry): entry.achievements.add(self.category) entry.save() def process_entry(self, entry): raise NotImplementedError() def __call__(self): log.info('Delete existing %s', self.category) self.delete_existings() log.info('Processing %s', self.category) for entry in self.get_queryset(): try: self.process_entry(entry) except Exception, e: log.error('Error while processing %s for %s', self.category, entry) log.exception(e)
["Home Improvement", ["41968", "3187", "20595", "41976","41986"]], ["Bedding", ["20469", "20445", "20450", "175750","43397"]] ], ["Cameras & Photo", ["Binoculars & Telescopes", ["83880", "74927", "162485", "74922","162044"]], ["Camera & Photo Accessories", ["29994", "162045", "29967", "155707","107894"]], ["Film Photography", ["182077", "15230", "4201", "29973","29980"]], ["Flashes & Flash Accessories", ["48515", "69573", "89161", "121464","155823"]] ] ] if categoriesPopulated == False: # Populating Categories for x in range(0, 5): parent = Category(name=categories_list[x][0]) parent.save() for i in range(1, 5): child = Category(name=categories_list[x][i][0], parent=parent) child.save() for j in range(0, 5): subChild = Category(name=categories_list[x][i][1][j], parent=child) subChild.save() print "Finished Populating Categories" if sellersPopulated == False: # Creating Pseudo-Sellers seller = [] for i in range(5): individ = Individual(username="******"+str(i)+"@gmail.com", email="seller"+str( i)+"@gmail.com", first_name=names[i], last_name=lasts[i], password="******")