示例#1
0
    def setUp(self):
        self.user = get_user_model().objects.create_user(
            'a_user', '*****@*****.**', 'a1234568')
        self.project = Project(name="Projectname",
                               name_short="proj",
                               creator=self.user)
        self.project.save()
        self.project.manager.add(self.user)
        self.short = self.project.name_short

        tag = Tag(project=self.project, tag_text="foo")
        tag.save()
        Issue(project=self.project, title="a").save()
        issue = Issue(project=self.project, title="b")
        issue.save()
        issue.tags.add(tag)

        # Uses the cookie hack from:
        # https://stackoverflow.com/questions/22494583/login-with-code-when-using-liveservertestcase-with-django
        client = Client()
        client.login(username='******', password='******')
        self.cookie = client.cookies['sessionid']
        self.selenium.get("{}{}".format(self.live_server_url,
                                        reverse('invite_users:invite_users')))
        self.selenium.add_cookie({
            'name': 'sessionid',
            'value': self.cookie.value,
            'secure': False,
            'path': '/'
        })
        self.selenium.refresh()
示例#2
0
文件: sync.py 项目: tyrchen/kagalaska
 def callback(info):
   items = info.pop('items', [])
   items = items or []
   info.update({'items': items})
   tag = Tag(**info)
   tag.save()
   print(info.get('name', ''))
示例#3
0
 def test_random_colors(self):
     colors = set()
     for i in range(len(Tag.COLORS)):
         tag = Tag(tag_text=str(i), project=self.p2)
         tag.save()
         colors.add(tag.color)
     self.assertEqual(colors, set([a for a, b in Tag.COLORS]))
示例#4
0
文件: views.py 项目: brxue/walkers
def new_article(request):
    if not request.user.is_authenticated():
        messages.error(request, "You must login firstly to creating a new article.")
        return HttpResponseRedirect(reverse(user_login))

    if request.method == "POST":
        form = ArticleForm(request.POST)
        if form.is_valid():
            article = form.save(commit=False)
            article.author = request.user
            article.save()
            form.save_m2m()
            for tag in form.cleaned_data['tags'].split(' '):
                try:
                    t = Tag.objects.get(name = tag)
                except Tag.DoesNotExist:
                    t = Tag(name=tag)
                    t.save()
                article.tags.add(t)
            article.save()
            return HttpResponseRedirect(reverse(show_article, kwargs={'pk': article.pk}))
    else:
        form = ArticleForm()

    return render(request, 'article/edit_article.html', {'form': form, 'new_article': 1})
示例#5
0
文件: views.py 项目: brxue/walkers
def edit_article(request, pk):
    if not request.user.is_authenticated():
        messages.error(request, "You must login firstly to edit an existing article.")
        return HttpResponseRedirect(reverse(user_login))

    article = get_object_or_404(Article, pk=pk)
    if article.author != request.user:
        raise Http404

    if request.method == "POST":
        form = ArticleForm(request.POST, instance=article)
        if form.is_valid():
            article = form.save(commit=False)
            article.author = request.user
            article.save()
            form.save_m2m()
            for tag in form.cleaned_data['tags'].split(' '):
                try:
                    t = Tag.objects.get(name = tag)
                except Tag.DoesNotExist:
                    t = Tag(name=tag)
                    t.save()
                article.tags.add(t)
            article.save()
            return HttpResponseRedirect(reverse(show_article, kwargs={'pk': article.pk}))
    else:
        form = ArticleForm(instance=article)

    return render(request, 'article/edit_article.html', {'form': form})
示例#6
0
    def _create_tags(self):
        taglist = (
            '環境',
            '地域',
            '人権',
            '教育',
            '医療',
            '介護',
            '国際協力',
            '文化',
            'スポーツ',
            '災害',
            '動物'
        )
        user = User.objects.get(pk=1)
        for t in taglist:
            tag = Tag(
                name=t,
            )
            tag.save()

        for user in User.objects.all():
            tag = Tag.objects.get(pk=(user.pk % len(taglist) + 1))
            user.follow_tag.add(tag)

        for i, event in enumerate(Event.objects.filter(contact="*****@*****.**")):
            if i < 20:
                event.tag.add(Tag.objects.get(name='環境'))
            elif i < 30:
                event.tag.add(Tag.objects.get(name='教育'))
            elif i < 35:
                event.tag.add(Tag.objects.get(name='介護'))
            elif i < 36:
                event.tag.add(Tag.objects.get(name='災害'))
示例#7
0
    def setUp(self):
        super(TestTextWord, self).setUp()

        Tag.setup_default()
        TextDifficulty.setup_default()

        self.instructor = self.new_instructor_client(Client())
        self.student = self.new_student_client(Client())
示例#8
0
    def test_search_for_tag(self):
        tag = Tag(tag_text='Test', project=self.project)
        tag.save()
        self.issue.tags.add(tag)

        result = SearchFrontend.query('test', self.user)
        self.assertEqual(len(result), 2)

        result = SearchFrontend.query('Issue.tags.tag_text ~~ "es"', self.user)
        self.assertEqual(len(result), 1)
示例#9
0
文件: sync.py 项目: tyrchen/kagalaska
 def _do_tag(self):
   b = BaseInput(self.tag_path)
   print("删除所有标签")
   Tag.delete_all()
   def callback(info):
     items = info.pop('items', [])
     items = items or []
     info.update({'items': items})
     tag = Tag(**info)
     tag.save()
     print(info.get('name', ''))
   b.input(callback)
示例#10
0
    def test_only_project_specific_tags_manageable(self):
        # create tags for p0
        tag_texts = ['test-tag', 'test-2', 'test-tag3', '3-crap', 't-4_crap']
        tags = []
        for tag_text in tag_texts:
            tag = Tag(tag_text=tag_text, project=Project.objects.get(name_short=p0_short))
            tag.save()
            tags.append(tag)

        # p0 tags are not part of p1
        response = self.client.get(reverse('tag:tag', kwargs={'project': p1_short}), follow=True)
        for tag in tag_texts:
            self.assertNotContains(response, tag)
示例#11
0
def add_book(request):
    context = dict()
    if request.method == "POST":
        if "url" in request.POST:
            url = request.POST["url"]
            context = parse_book_by_isbn(url)
            return render(request, "book/add.html", context)
        if "isbn" in request.POST:
            isbn = request.POST["isbn"]
            context = parse_book_by_isbn(isbn)
            book = Book()
            book.title = context["title"]
            book.publisher = context["publisher"]
            book.isbn = context["isbn"]
            book.url = context["url"]
            book.ispersonal = int(True)
            book.ownerid = request.user.id
            book.summary = context["summary"]
            book.price = context["price"]
            book.numraters = 0
            book.averageRate = 3
            book.created_date = datetime.datetime.now()
            book.updated_date = datetime.datetime.now()
            book.author = context["author"][0]
            book.authorinfo = context["author_intro"][0:4090]
            # print book.authorinfo
            book.catelog = context["catalog"][0:4090]
            book.pubdate = context["pubdate"]
            book.ispublic = int(True)
            book.imgurl = context["images"]
            book.city = Dper.objects.get(user_id=request.user.id).city
            book.bookcount = 1
            book.status = 1
            # Dper.objects.filter(id=request.user.id)[0].city
            book.save()

            # save tags of book
            for val in context["tags"]:
                tag = Tag()
                tag.value = val
                tag.createdate = datetime.datetime.now()
                tag.save()
                rel = Booktag()
                rel.tagid = tag.id
                rel.bookid = book.id
                rel.save()
            return redirect("/book/library", context)
    else:
        form = BookForm()
        context["form"] = form
        return render(request, "book/add.html", context)
示例#12
0
  def load(self):
    with open(name=self.path, mode='r') as f:
      for each_line in f.readlines():
        name, score, parents_ = each_line.decode('utf-8')[:-1].split('\t')
        parents = filter(None, parents_.split(','))
        tag = Tag.get_by_name(name)

        if not tag:
          item = Tag(name=name, score=float(score), parents=parents)
          item.save()
        else:
          tag.add_parents(parents=parents)

        print(name)
示例#13
0
 def test_tags_are_unique_per_project(self):
     tag_text = "please_don't_duplicate_me"
     t0 = Tag(tag_text=tag_text, project=Project.objects.get(name_short=p0_short))
     t0.save()
     with self.assertRaises(IntegrityError):
         t1 = Tag(tag_text=tag_text, project=Project.objects.get(name_short=p0_short))
         t1.save()
示例#14
0
    def setUpTestData(cls):
        # NOTE: if you modify those elements they need to be created in setUp, instead of here
        cls.user = get_user_model().objects.create_user('a', 'b', 'c')
        cls.project = Project(creator=cls.user, name_short='PRJ')
        cls.project.save()
        cls.project.manager.add(cls.user)
        cls.issue = Issue(title="Test-Issue",
                          project=cls.project,
                          kanbancol=cls.project.kanbancol.first(),
                          type="Bug")
        cls.issue.save()

        tag = Tag(tag_text='Test', project=cls.project)
        tag.save()
        cls.issue.tags.add(tag)
示例#15
0
  def load(self, to_db=False, to_tag=False, delete=False):
    with open(name=self.origin_path, mode='r') as f:
      for each_line in f.readlines():
        json_data = json.loads(each_line[:-1])
        save, format_data = self.format_info(json_data)
        if not save:
          continue

        try:
          slug = json_data.pop('slug')
          if delete:
            place = Place.get_by_slug(slug)
            if place:
              print("Will delete %s" %slug)
              place.remove()
            name_zh = json_data['name_zh']
            tag = Tag.get_by_name(name_zh)
            if tag:
              print("Will delete %s" %name_zh)
              tag.remove()

          if to_db:
            exists = Place.get_by_slug(slug=slug, json_format=True)
            if not exists:
              print(json_data['name_zh'])
              place = Place(slug=slug, **json_data)
              place.save()

          if to_tag:
            class_name = json_data.pop('class')
            name = json_data.get('name_zh', '')
            item = {'slug': slug, 'class': class_name}
            categories = json_data.get('categories', '')
            tag_type = class_name
            exists = Tag.get_by_name(name, json_format=True)
            if exists:
              print("存在 %s" %name)
              continue

            print(json_data['name_zh'])
            tag =   Tag(name=name, items=[item], score=float(DEFAULT_SCORE),
                      parents=categories, proxy=tag_type)

            tag.save()
            
        except Exception, err:
          print(err)
          continue
示例#16
0
  def to_cache(self):
    for tag in Tag.objects():
      name = tag.name
      parents = getattr(tag, 'parents', [])
      items = tag.get_items()['places']
      self.tags.update({
        name: {
          'parents': parents,
          'items': items
        }
      })

      for item in items:
        if not item['class'] in Tag.mapping:
          continue

        if self.has_slug(item['slug']):
          continue

        obj = Place.get_by_slug(item['slug'], json_format=True)
        if not obj:
          continue

        slug = obj.get('slug', '')
        if not slug:
          continue

        self.items.update({slug: obj})
示例#17
0
  def __init__(self, words_path=WORDS_PATH, chars_path=CHARS_PATH):
    path = Tag.cls_to_file(words_path)
    self.seg = Seg(path, chars_path)

    self.words_path = words_path if words_path else WORDS_PATH
    self.keywords = {}
    self._load()
示例#18
0
    def test_create_edit_issue_tags(self):
        # number of tags for the project self.project with short name proj_short
        response = self.client.get(
            reverse('project:tagac', kwargs={"project": proj_short}))
        response_json = response.json()
        self.assertEqual(len(response_json['results']),
                         len(Tag.objects.filter(project=self.project)))

        new_tag = Tag(project=self.project, tag_text='new_tag', color='YELLOW')
        new_tag.save()

        response = self.client.get(
            reverse('project:tagac', kwargs={"project": proj_short}))
        response_json = response.json()
        self.assertEqual(len(response_json['results']),
                         len(Tag.objects.filter(project=self.project)))
示例#19
0
  def remove(self, **json_data):
    name = json_data.get('name', '')
    if not self.memory_tags.exists(name):
      return

    self.memory_tags.delete(name)
    tag = Tag.get_by_name(name)
    tag.remove()
示例#20
0
    def handle(self, *args, **options):
        if len(args) == 0:
            medias = Media.objects.filter(is_local=False)
            logger.info("Atualizando todos as copias locais dos medias")
        else:
            since = int(args[0])
            some_day_ago = timezone.now().date() - timedelta(days=since)
            logger.info("Atualizando os medias desde o dia: " +
                        str(some_day_ago))
            medias = Media.objects.filter(date__gte=some_day_ago)

        for media in medias:
            try:

                # Synchronize/update tags.
                #
                # 1) Add all tags found in the git-annex metadata and not
                # already present on the media.
                # 2) If tags from other mucuas have been deleted (are missing in
                # the git_annex metadata tags), remove them from this media.
                tags_on_media = set(git_annex_list_tags(media))
                existing_tags = set(
                    (t.namespace, t.name) for t in media.tags.all())
                # Add new tags to media
                for t in tags_on_media - existing_tags:
                    # Add tag - search for existing, if none found create new tag.
                    namespace, name = t
                    try:
                        tag = Tag.objects.get(name=unicode(name),
                                              namespace=unicode(namespace))
                    except Tag.DoesNotExist:
                        tag = Tag(name=name, namespace=namespace)
                        tag.save()
                    media.tags.add(tag)

                # Remove tags that were removed on remote media
                for t in existing_tags - tags_on_media:
                    namespace, name = t
                    tag = Tag.objects.get(name=name, namespace=namespace)
                    media.tags.remove(tag)

                media.save(is_syncing=True)

            except OSError, e:
                logger.debug('Requested media not found: ' + media.name)
示例#21
0
    def setUp(self):
        super(TestTextWordTranslations, self).setUp()

        Tag.setup_default()
        TextDifficulty.setup_default()

        self.instructor = self.new_instructor_client(Client())
        self.student = self.new_student_client(Client())

        resp = self.instructor.post(reverse_lazy('text-api'),
                                    json.dumps(self.test_text_data),
                                    content_type='application/json')

        self.assertEquals(resp.status_code, 200, json.dumps(json.loads(resp.content.decode('utf8')), indent=4))

        resp_content = json.loads(resp.content.decode('utf8'))

        self.text = Text.objects.get(pk=resp_content['id'])
示例#22
0
  def get_names(self, **json_data):
    names = json_data.get('name', [])
    if not names:
      return

    if isinstance(names, basestring):
      names = [names, ]

    return Tag.get_many_by_names(names)
示例#23
0
 def get_article_list(self, order, tag, search):
     if search:
         return models.Article.objects.filter(
             Q(title__contains=search) | Q(text__contains=search))
     elif tag:
         return Tag.get_article_by_tag(tag)
     elif order:
         return models.Article.objects.all().order_by(order)
     return models.Article.objects.all().order_by('-created')
示例#24
0
def add_book(request):
    context = dict()
    if request.method == 'POST':
        if 'url' in request.POST:
            url = request.POST['url']    
            context = parse_book_by_url(url)
            return render(request, 'book/add.html', context)
        if 'bookid' in request.POST:
            bookid = request.POST['bookid']
            context = parse_book_by_id(bookid)
            book = Book()
            book.title = context['title']
            book.publisher = context['publisher']
            book.isbn = context['isbn10'] if 'isbn10' in context else context['isbn13']
            book.url = context['url']
            book.ispersonal = int(True)
            book.ownerid = request.user.id
            book.summary = context['summary']
            book.price = context['price']
            book.numraters = 0
            book.averageRate = 3
            book.created_date = datetime.datetime.now()
            book.updated_date = datetime.datetime.now()
            book.author = context['author'][0]
            book.pubdate = context['pubdate']
            book.ispublic = int(True)
            book.imgurl = context['images']
            book.save()

            #save tags of book
            for val in context['tags']:
                tag = Tag()
                tag.value = val
                tag.createdate = datetime.datetime.now()
                tag.save()
                rel = Booktag()
                rel.tagid = tag.id
                rel.bookid = book.id
                rel.save()
            return redirect('/book/library', context)
    else:    
        form = BookForm()
        context['form'] = form
        return render(request, 'book/add.html', context)
示例#25
0
 def get_queryset(self):
     """
     returns queryset that depends on the Article fields
     """
     if self.tag:
         try:
             return Tag.get_articles_by_tag(self.tag)
         except ObjectDoesNotExist:
             raise Http404
     return self.search_list
示例#26
0
    def handle(self, *args, **options):
        if len(args) == 0:
            medias = Media.objects.filter(is_local=False)
            logger.info("Atualizando todos as copias locais dos medias")
        else:
            since = int(args[0])
            some_day_ago = timezone.now().date() - timedelta(days=since)
            logger.info("Atualizando os medias desde o dia: " + str(some_day_ago))
            medias = Media.objects.filter(date__gte=some_day_ago)
        
        for media in medias:
            try:

                # Synchronize/update tags.  
                #
                # 1) Add all tags found in the git-annex metadata and not
                # already present on the media.
                # 2) If tags from other mucuas have been deleted (are missing in
                # the git_annex metadata tags), remove them from this media.
                tags_on_media = set(git_annex_list_tags(media))
                existing_tags = set((t.namespace, t.name) for t in media.tags.all())
                # Add new tags to media
                for t in tags_on_media - existing_tags:
                    # Add tag - search for existing, if none found create new tag.
                    namespace, name = t
                    try: 
                        tag = Tag.objects.get(name=unicode(name),
                                              namespace=unicode(namespace))
                    except Tag.DoesNotExist:
                        tag = Tag(name=name, namespace=namespace)
                        tag.save()
                    media.tags.add(tag)

                # Remove tags that were removed on remote media
                for t in existing_tags - tags_on_media:
                    namespace, name = t 
                    tag = Tag.objects.get(name=name, namespace=namespace)
                    media.tags.remove(tag) 

                media.save(is_syncing=True)

            except OSError, e:
                logger.debug('Requested media not found: ' + media.name)        
示例#27
0
    def setUpTestData(cls):
        # NOTE: if you modify those elements they need to be created in setUp, instead of here
        cls.user = get_user_model().objects.create_user(
            'test', '*****@*****.**', 'test1234')
        cls.user2 = get_user_model().objects.create_user(
            'tast', '*****@*****.**', 'test1234')
        cls.user3 = get_user_model().objects.create_user(
            'tust', '*****@*****.**', 'test1234')

        cls.project = Project(creator=cls.user, name_short=proj_short)
        cls.project.save()
        cls.project.developer.add(cls.user)

        cls.tag1 = Tag(project=cls.project, tag_text='backend', color='RED')
        cls.tag2 = Tag(project=cls.project, tag_text='frontend', color='BLUE')
        cls.tag1.save()
        cls.tag2.save()
        cls.kanbancol = KanbanColumn(project=cls.project,
                                     position=4,
                                     name='test')
        cls.kanbancol.save()
示例#28
0
  def load(self):
    with open(name=self.path, mode='r') as f:
      for each_line in f.readlines():
        name, score = each_line.decode('utf-8')[:-1].split('\t')
        tag = Tag.get_by_name(name)

        if not tag:
          continue
        else:
          tag.set_score(score=float(score))

        print(name)
示例#29
0
    def restore_object(self, attrs, instance=None):

        if instance:
            # Update existing instance
            instance.id = attrs.get('id', instance.id)
            instance.namespace = attrs.get('namespace', instance.namespace)
            instance.note = attrs.get('namespace', instance.note)
            instance.name = attrs.get('name', instance.name)

        return instance
        
        # Create new instance
        return Tag(**attrs)
示例#30
0
    def _create_tags(self):
        taglist = ('環境', '地域', '人権', '教育', '医療', '介護', '国際協力', '文化', 'スポーツ',
                   '災害', '動物')
        user = User.objects.get(pk=1)
        for t in taglist:
            tag = Tag(name=t, )
            tag.save()

        for user in User.objects.all():
            tag = Tag.objects.get(pk=(user.pk % len(taglist) + 1))
            user.follow_tag.add(tag)

        for i, event in enumerate(
                Event.objects.filter(contact="*****@*****.**")):
            if i < 20:
                event.tag.add(Tag.objects.get(name='環境'))
            elif i < 30:
                event.tag.add(Tag.objects.get(name='教育'))
            elif i < 35:
                event.tag.add(Tag.objects.get(name='介護'))
            elif i < 36:
                event.tag.add(Tag.objects.get(name='災害'))
示例#31
0
 def to_representation(self, instance):
     if 'request' in self._context:
         params = self._context['request'].query_params
         if 'lon' in params and 'lat' in params:
             lon = float(params['lon'])
             lat = float(params['lat'])
             p = GEOSGeometry('POINT(%f %f)' % (lon, lat), srid=4326)
             instance.origin = p
         if 'tags' in params and params['tags']:
             from tag.models import Tag
             tags = Tag.tags_from_param(params['tags'])
             instance.search_tags = tags
     return super(UserPlaceSerializer, self).to_representation(instance)
示例#32
0
 def create(self, request, *args, **kwargs):
     tag_info = Tag.objects.filter(tag_name=request.data.get('tag_name'),
                                   is_delete=0).all()
     if len(tag_info) == 0:
         tag = Tag()
         if 'tag_name' in request.data.keys():
             tag.tag_name = request.data['tag_name']
         if 'tag_remark' in request.data.keys():
             tag.tag_remark = request.data['tag_remark']
         tag.create_time = datetime.now()
         tag.update_time = datetime.now()
         tag.save()
         result = model_to_dict(tag)
         return Response(result, status=status.HTTP_201_CREATED)
     else:
         result = {'msg': '标签名称已存在'}
         return Response(data=result, status=status.HTTP_409_CONFLICT)
示例#33
0
def add_and_synchronize_tags(media, tags, mucua):
    """
    Add tags to media, synchronize with git-annex repository.
    """
    # Remove tags that originate in this mucua
    for tag in media.tags.filter(namespace__contains=mucua.uuid):
        media.tags.remove(tag)

    # Now add each tag in list.
    for tag in tags:
        if not tag or tag.isspace():
            continue
        try:
            tag = tag.strip()
            tag = Tag.objects.filter(name=tag)[0]
        except (Tag.DoesNotExist, IndexError):
            tag = Tag(name=tag, namespace=mucua.uuid + "-tag")
            # TODO: Handle namespaces!
            tag.save()

        media.tags.add(tag)

    # Synchronize tags
    # First, add new ones as metadata on files.
    tags = media.tags.all()
    existing_tags = git_annex_list_tags(media)
    for t in media.tags.all():
        if (t.namespace, t.name) not in existing_tags:
            git_annex_add_tag(media, t.namespace, t.name)
    # Then, *remove* tags that are no longer present. 
    # Only remove tags set with present namespace!
    for namespace, name in existing_tags:
        if namespace.startswith(mucua.uuid) and not (namespace, name) in [
            (t.namespace, t.name) for t in tags
            ]:
            git_annex_remove_tag(media, namespace, name)
示例#34
0
def add_and_synchronize_tags(media, tags, mucua):
    """
    Add tags to media, synchronize with git-annex repository.
    """
    # Remove tags that originate in this mucua
    for tag in media.tags.filter(namespace__contains=mucua.uuid):
        media.tags.remove(tag)

    # Now add each tag in list.
    for tag in tags:
        if not tag or tag.isspace():
            continue
        try:
            tag = tag.strip()
            tag = Tag.objects.filter(name=tag)[0]
        except (Tag.DoesNotExist, IndexError):
            tag = Tag(name=tag, namespace=mucua.uuid + "-tag")
            # TODO: Handle namespaces!
            tag.save()

        media.tags.add(tag)

    # Synchronize tags
    # First, add new ones as metadata on files.
    tags = media.tags.all()
    existing_tags = git_annex_list_tags(media)
    for t in media.tags.all():
        if (t.namespace, t.name) not in existing_tags:
            git_annex_add_tag(media, t.namespace, t.name)
    # Then, *remove* tags that are no longer present. 
    # Only remove tags set with present namespace!
    for namespace, name in existing_tags:
        if namespace.startswith(mucua.uuid) and not (namespace, name) in [
            (t.namespace, t.name) for t in tags
            ]:
            git_annex_remove_tag(media, namespace, name)
示例#35
0
  def handle(self, *args, **options):
    if args:
      path = args[0]
    else:
      path = DEFAULT_PATH

    tags = Tag.objects()
    first_line = '名字\t权重\t父标签\t等同于\t对应的元素\n'

    file = open(path, 'w')
    file.write(first_line.encode('utf-8'))
    for tag in tags:
      line = self.do_tag(tag)
      file.write(line)
    file.close()
示例#36
0
def create_tags():

	Tag.objects.all().delete()

	for pk, fields in tags.iteritems():
		tname = remove_accents(hashtagify(fields['name']))
		print "TAG", tname
		if Tag.objects.filter(tag__iexact=tname).count() == 0:
			t = Tag()
			t.tag = tname 
			t.title = fields['name'].strip()
			t.description = fields['description']
			t.client_domain = datea
			t.save()
示例#37
0
    def handle(self, *args, **options):
        u = []
        for i in range(10):
            u.append(User(name="user{}".format(i), date=timezone.now()))

        for usr in u:
            usr.save()

        t = []
        for i in range(10):
            t.append(Tag(name="tag{}".format(i)))

        for tag in t:
            tag.save()

        q = []
        i = 1
        for usr in u:
            q.append(
                Question(title="question{}".format(i),
                         text="Lorem ipsum question from user: {}".format(usr),
                         date=timezone.now(),
                         user=usr))
            i += 1

        for qst in q:
            qst.save()

        for qst in q:
            tags = qst.tags
            for i in range(3):
                tags.add(t[rnd.randint(0, 9)])
            qst.save()

        a = []
        for que in q:
            for usr in u:
                a.append(
                    Answer(
                        text="Lorem ipsum answer from user: {}".format(usr),
                        date=timezone.now(),
                        user=usr,
                        qst=que,
                    ))

        for ans in a:
            ans.save()
示例#38
0
文件: views.py 项目: duonghau/hoidap
 def post(self, request):
     form = QuestionForm(data=request.POST)
     if form.is_valid():
         question = Question(title=form.cleaned_data['title'],
                             content=form.cleaned_data['content'])
         question.author = request.user.profile
         question.save()
         for tagtitle in form.cleaned_data['tags']:
             try:
                 tag = Tag.objects.get(name=tagtitle)
             except ObjectDoesNotExist:
                 tag = Tag()
                 tag.name = tagtitle
                 tag.save()
             question.tags.add(tag)
             tag.save()
         question.author.rank += 0.01
         question.save()
         question.author.save()
         #notification
         users_notification = []
         for tag in question.tags.all():
             if tag.tag_followers.all().count() > 0:
                 for profile in tag.tag_followers.all():
                     if profile != request.user.profile and profile not in users_notification:
                         #create notification
                         notification = Notification()
                         notification.sender = request.user.profile
                         notification.recipient = profile
                         notification.action = 'addquestion'
                         notification.content_object = question
                         notification.save()
                         users_notification.append(profile)
         for follower in request.user.profile.followers.all():
             if follower not in users_notification:
                 notification = Notification()
                 notification.sender = request.user.profile
                 notification.recipient = follower
                 notification.action = 'addquestion'
                 notification.content_object = question
                 notification.save()
         return HttpResponseRedirect(
             reverse('question:detail', args=(question.pk, question.slug)))
     else:
         args = {}
         args['form'] = form
         args.update(csrf(request))
         return render(request, 'question_add.html', args)
示例#39
0
    def test_search_for_tag(self):
        tag1 = Tag(tag_text='Test', project=Project.objects.get(name_short=p0_short))
        tag1.save()
        tag2 = Tag(tag_text='Test-Tag', project=Project.objects.get(name_short=p0_short))
        tag2.save()

        result = SearchFrontend.query('test', self.user)
        self.assertEqual(len(result), 2)

        result = SearchFrontend.query('Test-Tag', self.user)
        self.assertEqual(len(result), 1)

        # test fieldcheckings
        result = SearchFrontend.query('Tag.project.name_short ~~ "a"', self.user)
        self.assertEqual(len(result), 0)

        # test permission check
        user = get_user_model().objects.create_user('b', '*****@*****.**', 'b1234567')
        result = SearchFrontend.query('test', user)
        self.assertEqual(len(result), 0)
示例#40
0
  def load(self):
    with open(name=self.path, mode='r') as f:
      for each_line in f.readlines():
        name, parents_str = each_line.decode('utf-8')[:-1].split('\t')
        parents = parents_str.split(',')
        print(name, parents)
        # To normal model
        exists = Normal.get_by_slug(name)
        if not exists:
          item = Normal(slug=name)
          print("Saving Normal Item %s" % name)
          item.save()

        for parent in parents:
          exists = Normal.get_by_slug(parent)
          if not exists:
            parent_item = Normal(slug=parent)
            print("Saving Normal Item %s" % parent)
            parent_item.save()

        # To tag model
        exists = Tag.get_by_name(name)
        if not exists:
          tag = Tag(name=name, parents=parents, score=self.score,
                    items=[{'slug': name, 'class': 'NORMAL'},],
                    proxy='NORMAL')
          print("Tag Item, %s" % name)
          tag.save()

        for parent in parents:
          exists = Tag.get_by_name(parent)
          if not exists:
            tag = Tag(name=parent, score=self.score,
                      items=[{'slug': parent, 'class': 'NORMAL'},],
                      proxy='NORMAL')
            print("Tag item %s " % parent)
            tag.save()
示例#41
0
文件: views.py 项目: duonghau/hoidap
 def post(self,request):
     form=QuestionForm(data=request.POST)
     if form.is_valid():
         question=Question(title=form.cleaned_data['title'],content=form.cleaned_data['content'])
         question.author=request.user.profile
         question.save()
         for tagtitle in form.cleaned_data['tags']:
             try:
                 tag=Tag.objects.get(name=tagtitle)
             except ObjectDoesNotExist:
                 tag=Tag()
                 tag.name=tagtitle
                 tag.save()
             question.tags.add(tag)
             tag.save()
         question.author.rank+=0.01
         question.save()
         question.author.save()
         #notification
         users_notification=[]
         for tag in question.tags.all():
             if tag.tag_followers.all().count() > 0:
                 for profile in tag.tag_followers.all():
                     if profile!=request.user.profile and profile not in users_notification:
                         #create notification
                         notification=Notification()
                         notification.sender=request.user.profile
                         notification.recipient=profile
                         notification.action='addquestion'
                         notification.content_object=question
                         notification.save()
                         users_notification.append(profile)
         for follower in request.user.profile.followers.all():
             if follower not in users_notification:
                 notification=Notification()
                 notification.sender=request.user.profile
                 notification.recipient=follower
                 notification.action='addquestion'
                 notification.content_object=question
                 notification.save()
         return HttpResponseRedirect(reverse('question:detail',args=(question.pk, question.slug)))
     else:
         args={}
         args['form']=form
         args.update(csrf(request))
         return render(request,'question_add.html',args)
示例#42
0
def add_book(request):
    context = dict()
    if request.method == 'POST':
        if 'url' in request.POST:
            url = request.POST['url']
            context = parse_book_by_url(url)
            return render(request, 'book/add.html', context)
        if 'bookid' in request.POST:
            bookid = request.POST['bookid']
            context = parse_book_by_id(bookid)
            book = Book()
            book.title = context['title']
            book.publisher = context['publisher']
            book.isbn = context['isbn10'] if 'isbn10' in context else context[
                'isbn13']
            book.url = context['url']
            book.ispersonal = int(True)
            book.ownerid = request.user.id
            book.summary = context['summary']
            book.price = context['price']
            book.numraters = 0
            book.averageRate = 3
            book.created_date = datetime.datetime.now()
            book.updated_date = datetime.datetime.now()
            book.author = context['author'][0]
            book.pubdate = context['pubdate']
            book.ispublic = int(True)
            book.imgurl = context['images']
            book.save()

            #save tags of book
            for val in context['tags']:
                tag = Tag()
                tag.value = val
                tag.createdate = datetime.datetime.now()
                tag.save()
                rel = Booktag()
                rel.tagid = tag.id
                rel.bookid = book.id
                rel.save()
            return redirect('/book/library', context)
    else:
        form = BookForm()
        context['form'] = form
        return render(request, 'book/add.html', context)
 def handle(self, *args, **options):
     wb = load_workbook(options['filepath'], use_iterators = True)
     ws = wb.worksheets[0]
     row_counter = 1
     newly_created_counter, updated_counter = 0, 0
     '''
     phone_num    gender    city        whatsup    high_school    college         occupations(3 tops)               tags(comma separated)
     1234567890    male    beijing      aaa            A中学            A大学        occupations1,occupations2        child1,child2, test
     1234567891            shanghai     bbb            B中学            B大学        occupations                        child11, child21, test11
     1234567892    female  guangzhou    ccc            C中学            C大学        child22, test21                  child22, test21
     '''
     name_occupation_dict = dict( (tag.name, tag) for tag in TreeTag.objects.get(slug='occupation-tag-root').get_descendants(include_self=False))
     name_tag_dict = dict( (tag.name, tag) for tag in Tag.objects.all() )
     name_high_school_dict = dict( (school.name, school) for school in School.objects.filter(type='high_school') )
     name_college_dict = dict( (school.name, school) for school in School.objects.filter(type='college') )
     for row in ws.iter_rows(row_offset=1):
         row_counter += 1
         phone_num = row[0].value or ''
         gender_str = (row[1].value or '').strip()
         if gender_str:
             gender = 1 if gender_str.lower()=='male' else 0
         else:
             gender = None 
         defaults = {
             'gender': gender,
             'city': row[2].value or '',
             'whatsup': row[3].value or '',
         }
         if row[4].value:
             defaults['high_school'] = name_high_school_dict.get(row[4].value.strip())
         if row[5].value:
             defaults['college'] = name_college_dict.get(row[5].value.strip())
         occupations_strs = re.split('[,锛� ]+', str( row[6].value or '' ))
         occupations = [ name_occupation_dict[tag_name] for tag_name in occupations_strs if tag_name in name_occupation_dict ]
         tag_strs = re.split('[,锛� ]+', str( row[7].value or '' ) )
         
         tags = []
         for tag_name in tag_strs:
             if tag_name in name_tag_dict:
                 tags.append(name_tag_dict[tag_name])
             else:
                 if not tag_name:
                     continue
                 tag = Tag(name=tag_name)
                 tag.save()
                 tags.append(tag)
                 name_tag_dict[tag_name] = tag
         print('phone_num', phone_num, 'defaults', defaults)
         try:
             phone_num = format_phonenumber(phone_num)
             profile, newly_created = Profile.objects.get_or_create(phone_num=phone_num, defaults=defaults)
         except Exception as e:
             raise CommandError('Line: %d encounter error: %s' % (row_counter, e, ) )
         else:
             if newly_created:
                 newly_created_counter += 1
             else:
                 for key, value in defaults.items():
                     setattr(profile, key, value)
                 profile.save()
                 updated_counter += 1
             if occupations:
                 profile.occupations.set(*occupations)
             if tag_strs:
                 # if the tag is not in the system it would create a new one
                 profile.tags.set(*tags)
     self.stdout.write('newly created: %d, updated: %d, total: %d' % (newly_created_counter, 
                                                                      updated_counter, 
                                                                      newly_created_counter+updated_counter, ) )
示例#44
0
 def _load(self):
   for tag in Tag.objects():
     score = getattr(tag, 'score', settings.NEW_WORD_DEFAULT_VALUE)
     self.add_word(tag.name, score)
示例#45
0
def create_campaigns():

	Campaign.objects.all().delete()

	for pk, fields in mapeos.iteritems():

		if pk in skip_mapeos:
			continue
		#get extra data
		#adata = json.load(urllib2.urlopen('http://datea.pe/api/v1/mapping/'+str(pk)+'/?format=json'))

		c = Campaign(pk=pk)
		c.user_id = get_user(fields['user']['id'])
		c.name = fields['name']
		c.published = fields['published']
		c.featured = fields['featured']
		c.short_description = fields['short_description']
		c.mission = fields['mission']
		c.information_destiny = fields['information_destiny']
		c.long_description = fields['long_description']
		c.client_domain = datea
		if fields['center']:
			c.center = GEOSGeometry(fields['center'])
		if fields['boundary']:
			c.boundary = GEOSGeometry(fields['boundary'])

		if fields['end_date']:
			c.end_date = date_parser(fields['end_date'])

		if fields['image']:
			c.image_id = fields['image']['id']

		c.category_id = fields['category']['id']

		# main hashtag
		if fields['hashtag']:
			tname = remove_accents(hashtagify(fields['hashtag'].replace('#', '')))
		else:
			tname = remove_accents(hashtagify(fields['name'].replace('#', '')))

		if Campaign.objects.filter(slug=slugify(tname)).count() == 0:
			c.slug = slugify(tname)
		else:
			c.slug = slugify(fields['slug'])


		print "CAMPAIGN TAG NAME", tname
		
		existing = Tag.objects.filter(tag__iexact=tname)
		if existing.count() == 0:
			t = Tag()
			t.tag = tname 
			t.title = fields['name'].strip()
			#t.description = fields['short_description']
			t.save()
			c.main_tag_id = t.pk
		else:
			c.main_tag_id = existing[0].pk
		c.save()

		# secondary tags (m2m after save)
		for ipk in fields['item_categories']:
			tag = find_tag(ipk)
			c.secondary_tags.add(tag)

		created = date_parser(fields['created'])
		modified = date_parser(fields['modified'])

		Campaign.objects.filter(pk=c.pk).update(created=created, modified=modified)
示例#46
0
def roadmap_id(request, roadmap_id):
    if request.method == "GET":
        if not request.user.is_authenticated:
            return HttpResponse(status=401)
        try:
            roadmap = Roadmap.objects.get(id=roadmap_id)
        except ObjectDoesNotExist:
            return HttpResponseNotFound()

        roadmap_dict = roadmap.to_dict()
        return JsonResponse(roadmap_dict)

    elif request.method == "PUT":
        if not request.user.is_authenticated:
            return HttpResponse(status=401)
        try:
            roadmap = Roadmap.objects.get(id=roadmap_id)
        except ObjectDoesNotExist:
            return HttpResponseNotFound()
        if not roadmap.author_id == request.user.id:
            return HttpResponseForbidden()
        try:
            req_data = json.loads(request.body.decode())
            new_private = req_data["private"]
            new_image_id = req_data["imageId"]
            new_title = req_data["title"]
            new_level = req_data["level"]
            new_description = req_data["description"]
            section_list = req_data["sections"]
            added_tag_list = req_data["addedTagList"]
            deleted_tag_list = req_data["deletedTagList"]

        except (KeyError, JSONDecodeError):
            return HttpResponseBadRequest()

        # Edit
        roadmap.delete_sections()
        roadmap.private = new_private
        roadmap.image_id = new_image_id
        roadmap.title = new_title
        roadmap.level = new_level
        roadmap.description = new_description
        for section in section_list:
            new_section = Section(title=section["section_title"],
                                  roadmap=roadmap)
            new_section.save()

            task_list = section["tasks"]
            for task in task_list:
                Task(
                    title=task["task_title"],
                    url=task["task_url"],
                    type=task["task_type"],
                    description=task["task_description"],
                    roadmap=roadmap,
                    section=new_section,
                ).save()

        # Set default value or non-changing
        roadmap.date = datetime.now()
        roadmap.progress = 1

        roadmap.save()

        # Delete tags in roadmap
        for tag in deleted_tag_list:
            tag_query = roadmap.tags.filter(tag_name__iexact=tag)
            if tag_query.exists():
                target_tag = tag_query.first()
                target_tag.decrement_count_roadmap()
                target_tag.save()
                roadmap.tags.remove(target_tag)

        # Add new tags m2m field in roadmap
        for tag in added_tag_list:
            tag_query = Tag.objects.filter(tag_name__iexact=tag)
            if tag_query.exists():
                target_tag = tag_query.first()
                roadmap.tags.add(target_tag)
                target_tag.increment_count_roadmap()
                target_tag.save()
            else:
                new_tag = Tag(tag_name=tag)
                new_tag.increment_count_roadmap()
                new_tag.save()
                roadmap.tags.add(new_tag)

        roadmap.save()
        roadmap_dict_simple = roadmap.to_dict_simple()
        return JsonResponse(roadmap_dict_simple, status=200)

    elif request.method == "DELETE":
        if not request.user.is_authenticated:
            return HttpResponse(status=401)
        try:
            roadmap = Roadmap.objects.get(id=roadmap_id)
        except ObjectDoesNotExist:
            return HttpResponseNotFound()
        if not roadmap.author_id == request.user.id:
            return HttpResponseForbidden()

        for tag in roadmap.tags.all():
            tag.decrement_count_roadmap()
            tag.save()

        roadmap.delete()
        return HttpResponse(status=204)

    elif request.method == "POST":
        if not request.user.is_authenticated:
            return HttpResponse(status=401)
        try:
            roadmap = Roadmap.objects.get(id=roadmap_id)
        except ObjectDoesNotExist:
            return HttpResponseNotFound()

        new_roadmap = Roadmap(
            private=roadmap.private,
            image_id=roadmap.image_id,
            title=roadmap.title,
            level=roadmap.level,
            description=roadmap.description,
            original_author=roadmap.author,
            author=request.user,
        )
        new_roadmap.save()

        # Add copied tags m2m fields
        for tag in roadmap.tags.all():
            new_roadmap.tags.add(tag)
            tag.increment_count_roadmap()
            tag.save()
        new_roadmap.save()

        # Add copied sections and tasks
        for section in roadmap.section_roadmap.all():
            new_section = Section(title=section.title, roadmap=new_roadmap)
            new_section.save()

            for task in section.task_section.all():
                Task(
                    title=task.title,
                    url=task.url,
                    type=task.type,
                    description=task.description,
                    roadmap=new_roadmap,
                    section=new_section,
                ).save()

        # Post response
        roadmap_dict_simple = new_roadmap.to_dict_simple()
        return JsonResponse(roadmap_dict_simple, status=201)
示例#47
0
 def to_cache(self):
   """
   考虑load的时候通过文件
   """
   for tag in Tag.objects():
     self.add_tag(tag)
示例#48
0
def create_objects_from_files(repository=get_default_repository().name):
    """Recria os midias no Django a partir dos medias serializados em JSON."""
    try:
        repository = Repository.objects.get(
            name=repository)
    except Repository.DoesNotExist:
        return None

    logger.info(u">>> %s" % _('DESERIALIZING'))
    logger.info(u"%s: %s" % (_('Repository'),  repository))
    #logger.debug(u"%s \n %s" % (_('List of media found in repository..'), get_latest_media(repository)))
    try:
        for serialized_media in get_latest_media(repository):
            logger.info(u"%s: %s" % (_('Serialized Media'), serialized_media))
            media_json_file_path = os.path.join(REPOSITORY_DIR,
                                                repository.name,
                                                serialized_media)
            if os.path.isfile(media_json_file_path):
                with  open(media_json_file_path) as media_json_file:
		    try:
                        data = JSONParser().parse(media_json_file)
                    except:
                        print u"Problem parsing JSON: " + media_json_file.read()
                        continue

                try:
                    media = Media.objects.get(uuid=data["uuid"])
                    serializer = MediaSerializer(media, data=data, partial=True)
                    print serializer.is_valid()
                    print serializer.errors
                    serializer.object.save(is_syncing=True)
                    logger.info(u"%s" % _('This media already exist. Updated.'))
                except Media.DoesNotExist:
                    serializer = MediaSerializer(data=data)
                    print serializer.is_valid()
                    print serializer.errors
                    serializer.object.save(is_syncing=True)
                    media = serializer.object
                    logger.info(u"%s" % _('New media created'))

                # Synchronize/update tags.  
                #
                # 1) Add all tags found in the git-annex metadata and not
                # already present on the media.
                # 2) If tags from other mucuas have been deleted (are missing in
                # the git_annex metadata tags), remove them from this media.
                tags_on_media = set(git_annex_list_tags(media))
                existing_tags = set((t.namespace, t.name) for t in media.tags.all())
                # Add new tags to media
                for t in tags_on_media - existing_tags:
                    # Add tag - search for existing, if none found create new tag.
                    namespace, name = t
                    try: 
                        tag = Tag.objects.get(name=unicode(name),
                                              namespace=unicode(namespace))
                    except Tag.DoesNotExist:
                        tag = Tag(name=name, namespace=namespace)
                        tag.save()
                    media.tags.add(tag)

                # Remove tags that were removed on remote media
                for t in existing_tags - tags_on_media:
                    namespace, name = t 
                    tag = Tag.objects.get(name=name, namespace=namespace)
                    media.tags.remove(tag) 
             

    except CommandError:
        pass
示例#49
0
    def setUp(self) -> None:
        super(TestData, self).setUp()

        Tag.setup_default()
        TextDifficulty.setup_default()
示例#50
0
import random as rnd

from user.models import User
from tag.models import Tag
from question.models import Question
from answer.models import Answer
from like.models import Like

u = []
for i in range(10):
    u.append(User(name="user{}".format(i), date=timezone.now()))
    u[i].save()

t = []
for i in range(10):
    t.append( Tag(name="tag{}".format(i)) )
    t[i].save()

q = []
for usr in u:
    for i in range(10):
        q.append(
            Question(
                title = "question{}".format(i),
                text = "Lorem ipsum hello from {}".format(i),
                date = timezone.now(),
                user = usr
            )
        )
        q[i].save()
示例#51
0
    def setUp(self):
        # create user
        self.client = Client(enforce_csrf_checks=False)
        user = User.objects.create_user(username="******", email="test", password="******")

        # create Tags
        tag_black = Tag(name="black", user=user)
        tag_black.save()
        tag_white = Tag(name="white", user=user)
        tag_white.save()
        tag_red = Tag(name="red", user=user)
        tag_red.save()
        tag_fancy = Tag(name="fancy", user=user)
        tag_fancy.save()
        tag_verypretty = Tag(name="verypretty", user=user)
        tag_verypretty.save()

        # create Items
        item1 = Item(category="Outer", user=user)
        item1.save()
        item1.tags.add(tag_black, tag_white)
        item2 = Item(category="UpperBody", user=user)
        item2.save()
        item2.tags.add(tag_black, tag_red)
        item3 = Item(category="Accessories", user=user)
        item3.save()
        item3.tags.add(tag_black, tag_fancy)
        item4 = Item(category="verypretty", user=user)
        item4.save()
        item4.tags.add(tag_verypretty)

        # create Outfit
        outfit1 = Outfit(user=user, image_link="", date="2019-11-11", tempAvg=3, tempIcon="happy", satisfaction=5)
        outfit1.save()
        outfit1.items.add(item1, item2, item3, item4)
        outfit1.save()
示例#52
0
    def test_parser(self):
        # contains test strings and the expected length of the attrs_to_set list
        # the third field indicates whether an issue shoud have been created
        tag = Tag(project=self.project, tag_text="testtag")
        tag.save()
        tag2 = Tag(project=self.project, tag_text="zweitertag")
        tag2.save()

        tests = [
            ['Fancy task :Task &Todo', 2, True],
            [
                'Another fancy task :Bug !2 #testtag @a ;with description', 5,
                True
            ],
            ['>PRJ-1 !2 :Bug', 2, False],
            ['>2 $8', 1, False],
        ]

        for t in tests:
            parser.compile(t[0], self.project, self.user)
            self.assertEqual(len(parser.attrs_to_set), t[1])
            self.assertEqual(parser.issue_created, t[2])
            # all the above expressions should set issue_changed to True
            self.assertEqual(parser.issue_changed, True)

        # now we should have two new issues, check also their numbers
        self.assertEqual(Project.objects.first().issue.count(), 2)
        self.assertEqual(Issue.objects.filter(title="Fancy task").count(), 1)
        self.assertEqual(
            Issue.objects.filter(project=self.project, number=1).count(), 1)
        self.assertEqual(
            Issue.objects.filter(project=self.project,
                                 number=1).first().creator, self.user)
        self.assertEqual(
            Issue.objects.filter(project=self.project,
                                 number=1).first().kanbancol.name, 'Todo')
        self.assertEqual(
            Issue.objects.filter(project=self.project, number=2).count(), 1)
        self.assertEqual(
            Issue.objects.filter(project=self.project,
                                 number=2).first().storypoints, 8)
        self.assertEqual(
            Issue.objects.filter(project=self.project,
                                 number=2).first().description,
            'with description')
        self.assertEqual(
            Issue.objects.filter(project=self.project,
                                 number=2).first().creator, self.user)

        # validate that fancy task is of type bug
        self.assertEqual(
            Issue.objects.filter(title="Fancy task", type="Bug").count(), 1)

        # validate that Another fancy task is of type bug with given attributes
        self.assertEqual(
            Issue.objects.filter(title="Another fancy task",
                                 type="Bug",
                                 priority=2,
                                 assignee=self.user,
                                 tags=tag).count(), 1)

        # set description of Another fancy task
        parser.compile('>PRJ-2 ;new description', self.project, self.user)
        self.assertEqual(
            Issue.objects.filter(project=self.project,
                                 number=2).first().description,
            'new description')

        # set kanbancol of Fancy task
        parser.compile('>PRJ-1 &Progr', self.project, self.user)
        self.assertEqual(
            Issue.objects.filter(project=self.project,
                                 number=1).first().kanbancol.name,
            'In Progress')

        # test icontains when setting kanbancol
        self.assertRaises(Exception, parser.compile, '>PRJ-1 &done',
                          self.project, self.user)
        self.assertEqual(
            Issue.objects.filter(project=self.project,
                                 number=1).first().kanbancol.name,
            'In Progress')

        parser.compile('>PRJ-1 &Done', self.project, self.user)
        self.assertEqual(
            Issue.objects.filter(project=self.project,
                                 number=1).first().kanbancol.name, 'Done')

        # add second tag and new assignee to PRJ2 and validate
        currentID = self.project.nextTicketId
        parser.compile('>PRJ-2 #zweitertag @d', self.project, self.user)
        issue = Issue.objects.get(title="Another fancy task")
        self.assertEqual(parser.issue_created, False)
        self.assertEqual(parser.issue_changed, True)
        self.assertEqual(parser.issue_to_change, issue)
        self.assertEqual(issue.tags.count(), 2)
        self.assertEqual(issue.assignee.count(), 2)
        self.assertIn(self.user, issue.assignee.all())
        self.assertIn(self.user2, issue.assignee.all())
        self.assertEqual(issue.number, 2)
        self.project.refresh_from_db()
        self.assertEqual(currentID, self.project.nextTicketId)

        # test permission checks and validations
        user = get_user_model().objects.create_user('g', 'h', 'i')
        issue.tags.clear()
        issue.refresh_from_db
        self.assertEqual(issue.tags.count(), 0)

        # not existing issues may not be edited and nextTicketId must not change
        currentID = self.project.nextTicketId
        self.assertRaises(Exception, parser.compile, '>PRJ-3 #zweitertag @d',
                          self.project, self.user)
        self.project.refresh_from_db()
        self.assertEqual(currentID, self.project.nextTicketId)

        # user must not edit projects to which he has no devel access
        self.assertRaises(Exception, parser.compile, '>PRJ-2 #zweitertag @d',
                          self.project, user)

        # only users with access to project may be set as assignee
        self.assertRaises(Exception, parser.compile, '>PRJ-2 #zweitertag @g',
                          self.project, self.user)

        # tags must not have changed
        issue.refresh_from_db
        self.assertEqual(issue.tags.count(), 0)

        # create another tag containing a space
        tag = Tag(project=self.project, tag_text="tag with spaces")
        tag.save()
        parser.compile('>PRJ-2 #tag with spaces @d', self.project, self.user)
        self.assertEqual(parser.issue_changed, True)
        issue.refresh_from_db()
        self.assertEqual(issue.tags.filter(pk=tag.pk).count(), 1)

        # dependent issue must exist and be in the same project
        parser.compile('Test-Issue proj2 :Bug', self.project2, self.user)
        self.assertEqual(parser.issue_created, True)
        self.assertEqual(parser.issue_changed, True)
        issue = Issue.objects.get(title="Test-Issue proj2")
        self.assertEqual(parser.issue_to_change, issue)
        self.assertEqual(
            Issue.objects.filter(project=self.project2).count(), 1)
        self.assertRaises(Exception, parser.compile, '>TPJ-1 ~PRJ-1',
                          self.project, self.user)

        # log time to issue
        parser.compile('>PRJ-1 +2h5m', self.project, self.user)
        self.assertEqual(parser.issue_created, False)
        # logging time is no change action
        self.assertEqual(parser.issue_changed, False)
        t = Timelog.objects.get(issue__title='Fancy task')
        self.assertEqual(t.time.total_seconds(), 7500)

        # log many times to issue
        parser.compile('>PRJ-1 +2h5m +1m', self.project, self.user)
        self.assertEqual(parser.issue_created, False)
        self.assertEqual(parser.issue_changed, False)
        self.assertEqual(
            Timelog.objects.filter(issue__title='Fancy task').count(), 3)
        totaltime = 0
        for log in Timelog.objects.filter(issue__title='Fancy task'):
            totaltime += log.time.total_seconds()
        self.assertEqual(totaltime, 15060)

        # log time to new issue
        issuetitle = 'Timelog-test-issue'
        parser.compile(issuetitle + ' +2h5m', self.project, self.user)
        self.assertEqual(parser.issue_created, True)
        self.assertEqual(parser.issue_changed, False)
        self.assertEqual(Issue.objects.filter(title=issuetitle).count(), 1)
        t = Timelog.objects.get(issue__title=issuetitle)
        self.assertEqual(t.time.total_seconds(), 7500)

        # test empty timelog field (must not create new timelog object, should still be 3)
        parser.compile('>PRJ-1 +', self.project, self.user)
        self.assertEqual(parser.issue_created, False)
        self.assertEqual(parser.issue_changed, False)
        self.assertEqual(
            Timelog.objects.filter(issue__title='Fancy task').count(), 3)

        # some syntactic stuff that should fail
        tests = [
            'Test-String ',
            '> @a',
            '>PRJ-2',
        ]

        for t in tests:
            self.assertRaises(Exception, parser.compile, t, self.project,
                              self.user)

        # tests for contains checks of tag
        Issue.objects.get(title='Fancy task').tags.clear()
        self.assertRaises(Exception, parser.compile, '>PRJ-1 #tag',
                          self.project, self.user)
        self.assertEqual(Issue.objects.get(title='Fancy task').tags.count(), 0)
        parser.compile('>PRJ-1 #ttag', self.project, self.user)
        self.assertEqual(Issue.objects.get(title='Fancy task').tags.count(), 1)
        self.assertEqual(parser.issue_created, False)
        self.assertEqual(parser.issue_changed, True)

        tag3 = Tag(project=self.project, tag_text="ttag")
        tag3.save()
        parser.compile('>PRJ-1 #ttag', self.project, self.user)
        self.assertEqual(parser.issue_changed, True)
        self.assertEqual(Issue.objects.filter(tags=tag3).count(), 1)
        self.assertEqual(Issue.objects.get(title='Fancy task').tags.count(), 2)

        # check that searching for tag is case insensitive
        Issue.objects.get(title='Fancy task').tags.clear()
        parser.compile('>PRJ-1 #teStTaG', self.project, self.user)
        self.assertEqual(Issue.objects.get(title='Fancy task').tags.count(), 1)
        self.assertEqual(parser.issue_created, False)
        self.assertEqual(parser.issue_changed, True)

        # same for user
        Issue.objects.get(title='Fancy task').assignee.clear()
        user3 = get_user_model().objects.create_user('jj', 'x', 'x')
        self.project.developer.add(user3)
        user4 = get_user_model().objects.create_user('jjj', 'y', 'y')
        self.project.developer.add(user4)
        user5 = get_user_model().objects.create_user('kj', 'z', 'z')
        self.project.developer.add(user5)
        self.assertRaises(Exception, parser.compile, '>PRJ-1 @j', self.project,
                          self.user)
        self.assertEqual(
            Issue.objects.get(title='Fancy task').assignee.count(), 0)
        parser.compile('>PRJ-1 @jj', self.project, self.user)
        self.assertEqual(parser.issue_created, False)
        self.assertEqual(parser.issue_changed, True)
        self.assertEqual(
            Issue.objects.filter(title='Fancy task', assignee=user3).count(),
            1)
        parser.compile('>PRJ-1 @jjj', self.project, self.user)
        self.assertEqual(parser.issue_created, False)
        self.assertEqual(parser.issue_changed, True)
        self.assertEqual(
            Issue.objects.filter(title='Fancy task', assignee=user4).count(),
            1)

        # user search case insensitive
        Issue.objects.get(title='Fancy task').assignee.clear()
        parser.compile('>PRJ-1 @jJJ', self.project, self.user)
        self.assertEqual(parser.issue_created, False)
        self.assertEqual(parser.issue_changed, True)
        self.assertEqual(
            Issue.objects.filter(title='Fancy task', assignee=user4).count(),
            1)

        # check that setting more than one assignee is possible
        parser.compile('>PRJ-1 @a @jj @kj', self.project, self.user)
        self.assertEqual(parser.issue_created, False)
        self.assertEqual(parser.issue_changed, True)
        self.assertEqual(
            Issue.objects.get(title='Fancy task').assignee.count(), 4)
        parser.compile('>PRJ-1 @jj', self.project, self.user)
        self.assertEqual(parser.issue_created, False)
        self.assertEqual(parser.issue_changed, True)
        self.assertEqual(
            Issue.objects.get(title='Fancy task').assignee.count(), 4)

        # test add depends functionality
        parser.compile('New issue depending on PRJ-1 ~PRJ-1', self.project,
                       self.user)
        self.assertEqual(parser.issue_created, True)
        self.assertEqual(parser.issue_changed, True)
        self.assertEqual(
            Issue.objects.filter(project=self.project,
                                 title='New issue depending on PRJ-1').count(),
            1)
        self.assertEqual(
            Issue.objects.get(
                project=self.project,
                title='New issue depending on PRJ-1').dependsOn.count(), 1)
        parser.compile('>PRJ-1 ~PRJ-2', self.project, self.user)
        self.assertEqual(parser.issue_created, False)
        self.assertEqual(parser.issue_changed, True)
        self.assertEqual(
            Issue.objects.get(title='Fancy task').dependsOn.count(), 1)

        # tag not existant
        Issue.objects.get(title='Fancy task').tags.clear()
        self.assertRaises(Exception, parser.compile, '>PRJ-1 #imnothere',
                          self.project, self.user)
        self.assertEqual(Issue.objects.get(title='Fancy task').tags.count(), 0)

        # user not existant
        Issue.objects.get(title='Fancy task').assignee.clear()
        self.assertRaises(Exception, parser.compile, '>PRJ-1 @imnothere',
                          self.project, self.user)
        self.assertEqual(
            Issue.objects.get(title='Fancy task').assignee.count(), 0)

        # test omitting project shortname in depends and modify tag
        Issue.objects.get(title='Fancy task').dependsOn.clear()
        parser.compile('>1 ~2', self.project, self.user)
        self.assertEqual(parser.issue_created, False)
        self.assertEqual(
            Issue.objects.get(title='Fancy task').dependsOn.count(), 1)
        self.assertEqual(
            Issue.objects.get(title='Fancy task').dependsOn.first().title,
            'Another fancy task')

        # check permissions test for issue to modify
        user5 = get_user_model().objects.create_user('tt', 'hh', 'ii')
        self.assertNotEqual(Issue.objects.get(title='Fancy task').priority, 4)
        self.assertRaises(Exception, parser.compile, '>1 !4', self.project,
                          user5)
        self.assertNotEqual(Issue.objects.get(title='Fancy task').priority, 4)

        # check that managers and (managers & developers) are valid as assignee
        u_manager = get_user_model().objects.create_user('manager', 'ma', 'ma')
        u_maneloper = get_user_model().objects.create_user(
            'maneloper', 'mar', 'mar')
        self.project.manager.add(u_manager)
        self.project.manager.add(u_maneloper)
        self.project.developer.add(u_maneloper)

        Issue.objects.get(title='Fancy task').assignee.clear()
        parser.compile('>PRJ-1 @manager @maneloper', self.project, self.user)
        self.assertEqual(parser.issue_created, False)
        self.assertEqual(parser.issue_changed, True)
        self.assertEqual(
            Issue.objects.filter(
                Q(title='Fancy task')
                & (Q(assignee=u_manager) | Q(assignee=u_maneloper))).count(),
            2)

        # check that first and last name is also valid when searching for users
        parser.compile('>PRJ-1 @alice @bob', self.project, self.user)
        issue = self.project.issue.get(number=1)
        self.assertIn(self.user, issue.assignee.all())
        self.assertIn(self.user2, issue.assignee.all())
        self.assertIn(u_manager, issue.assignee.all())
        self.assertIn(u_maneloper, issue.assignee.all())
        self.assertEqual(issue.assignee.count(), 4)
        parser.compile('>PRJ-1 @alice @Blub', self.project, self.user)
        issue.refresh_from_db()
        self.assertIn(self.user, issue.assignee.all())
        self.assertIn(self.user2, issue.assignee.all())
        self.assertIn(u_manager, issue.assignee.all())
        self.assertIn(u_maneloper, issue.assignee.all())
        self.assertEqual(issue.assignee.count(), 4)

        # check that user is not assigned more than once
        Issue.objects.get(title='Fancy task').assignee.clear()
        parser.compile('>PRJ-1 @alice @Bla', self.project, self.user)
        issue.refresh_from_db()
        self.assertIn(self.user, issue.assignee.all())
        self.assertEqual(issue.assignee.count(), 1)

        # check that no issue is created with error in change expression
        self.project.refresh_from_db()
        currentID = self.project.nextTicketId
        currentTicketCount = self.project.issue.count()
        self.assertRaises(Exception, parser.compile,
                          'New Issue #nonexistanttag', self.project, self.user)
        self.project.refresh_from_db()
        self.assertEqual(currentID, self.project.nextTicketId)
        self.assertEqual(currentTicketCount, self.project.issue.count())

        # check that issue creation without change expression is possible
        self.project.refresh_from_db()
        currentID = self.project.nextTicketId
        currentTicketCount = self.project.issue.count()
        title = 'Fancy new issue without chgxpr'
        parser.compile(title, self.project, self.user)
        self.assertEqual(parser.issue_created, True)
        self.assertEqual(parser.issue_changed, False)
        self.project.refresh_from_db()
        self.assertEqual(self.project.issue.filter(title=title).count(), 1)
        self.assertEqual(currentID + 1, self.project.nextTicketId)
        self.assertEqual(currentTicketCount + 1, self.project.issue.count())

        # check that changing an issue without change expression throws an exception
        self.assertRaises(Exception, parser.compile, '>1', self.project,
                          self.user)
示例#53
0
def roadmap(request):
    if request.method == "POST":
        if not request.user.is_authenticated:
            return HttpResponse(status=401)
        try:
            req_data = json.loads(request.body.decode())
            new_private = req_data["private"]
            new_image_id = req_data["imageId"]
            new_title = req_data["title"]
            new_level = req_data["level"]
            new_description = req_data["description"]
            section_list = req_data["sections"]
            tag_list = req_data["tags"]
        except (KeyError, JSONDecodeError):
            return HttpResponseBadRequest()

        new_roadmap = Roadmap(
            private=new_private,
            image_id=new_image_id,
            title=new_title,
            level=new_level,
            description=new_description,
            original_author=request.user,
            author=request.user,
        )
        new_roadmap.save()

        # Add tags m2m field in new_roadmap
        for tag in tag_list:
            tag_query = Tag.objects.filter(tag_name__iexact=tag)
            if tag_query.exists():
                target_tag = tag_query.first()
                new_roadmap.tags.add(target_tag)
                target_tag.increment_count_roadmap()
                target_tag.save()

            else:
                new_tag = Tag(tag_name=tag)
                new_tag.increment_count_roadmap()
                new_tag.save()
                new_roadmap.tags.add(new_tag)

        new_roadmap.save()

        # Add sections and tasks of this roadmap
        for section in section_list:
            new_section = Section(title=section["section_title"],
                                  roadmap=new_roadmap)
            new_section.save()

            task_list = section["tasks"]
            for task in task_list:
                Task(
                    title=task["task_title"],
                    url=task["task_url"],
                    type=task["task_type"],
                    description=task["task_description"],
                    roadmap=new_roadmap,
                    section=new_section,
                ).save()

        # Post response
        roadmap_dict_simple = new_roadmap.to_dict_simple()
        return JsonResponse(roadmap_dict_simple, status=201)

    return HttpResponseNotAllowed(["POST"])
示例#54
0
    def test_assign_tag_view(self):
        issue = Issue(title="Test-Issue",
                      project=self.project,
                      kanbancol=self.column,
                      type="Bug")
        issue.save()
        t0 = 'first_tag'
        tag0 = Tag(tag_text=t0, project=self.project)
        tag0.save()
        t1 = 'second_tag'
        tag1 = Tag(tag_text=t1, project=self.project)
        tag1.save()
        t2 = 'third_tag'
        tag2 = Tag(tag_text=t2, project=self.project)
        tag2.save()
        values = {
            # first_tag
            'tags': (1)
        }
        response = self.client.post(
            reverse('issue:edit',
                    kwargs={
                        'project': self.project.name_short,
                        'sqn_i': 1
                    }), values)
        # please don't ask me why the following (which would be a way better assert) doesn't work
        # self.assertContains(response, t0)
        self.assertIn(t0, str(response.content))
        self.assertEqual(Issue.objects.count(), 1)
        # TODO
        """
        self.assertEqual(issue.tags.count(), 1)
        self.assertEqual(issue.tags.first().text, t0)
        """
        response = self.client.get(
            reverse('issue:edit',
                    kwargs={
                        'project': self.project.name_short,
                        'sqn_i': 1
                    }))

        return
        # TODO TODO TODO the following doesn't work because t0 doesn't appear in the response anymore
        self.assertContains(response, t0)
        # self.assertIn(t0, str(response.content))
        values = {
            # 'tags': [t2, t1],
            'tags': [(3), (2)],
        }
        response = self.client.post(
            reverse('issue:edit',
                    kwargs={
                        'project': self.project.name_short,
                        'sqn_i': 1
                    }), values)
        self.assertContains(response, t0)
        self.assertContains(response, t2)
        self.assertContains(response, t1)

        response = self.client.get(
            reverse('issue:edit',
                    kwargs={
                        'project': self.project.name_short,
                        'sqn_i': 1
                    }))
        self.assertContains(response, t0)
        self.assertContains(response, t2)
        self.assertContains(response, t1)
示例#55
0
 def test_delete_all(self):
     tags = ['tag0_project0', 'tag0_project1', 'tag0_project2', 'tag0_project3']
     tag0 = Tag(tag_text=tags[0], project=self.project0, color="ef2929")
     tag1 = Tag(tag_text=tags[1], project=self.project0, color="ef2929")
     tag2 = Tag(tag_text=tags[2], project=self.project0, color="ef2929")
     tag3 = Tag(tag_text=tags[3], project=self.project0, color="ef2929")
     tag0.save()
     tag1.save()
     tag2.save()
     tag3.save()
     self.selenium.get("{}{}".format(self.live_server_url, reverse('tag:tag', kwargs={'project': self.p0_short})))
     self.selenium.find_element(By.ID, 'id_select_all').click()
     self.selenium.find_element(By.ID, 'id_delete-tags').find_element(By.ID, 'id_submit_delete_tags').click()
     for tag in tags:
         self.assertNotIn(tag, self.selenium.page_source)