Example #1
0
 def handle(self, *args, **options):
     n = 20
     tags = lorem.words(n)
     for tag in tags:
         t = Tag(title = tag)
         t.save()
     self.stdout.write(self.style.SUCCESS('Base successfully created. Add "%s" new tags' % n))
Example #2
0
    def handle(self, *args, **kwargs):
        total = kwargs['total']

        for i in range(total):

            t = Tag(title=fake.word())
            t.save()
Example #3
0
    def handle(self, *args, **options):
        tags = [
            'javascript', 'java', 'php', 'android', 'jquery', 'python',
            'html', 'css', 'c++', 'ios', 'mysql', 'sql',
            'iphone', 'angularjs', 'regexp', 'mail.ru',
            'technopark', 'WEB', 'gunicorn', 'nginx',
            'apache', 'django', 'valgrind', 'PHP',
            'HTML'
        ]

        for tag in tags:
            if len(Tag.objects.filter(text=tag)) == 0:
                t = Tag()

                t.text = tag
                t.save()

        number = int(options['number'])

        tags = Tag.objects.all()

        for q in Question.objects.all():
            self.stdout.write('question [%d]' % q.id)
            if len(q.tags.all()) < number:
                for i in range(0, number - len(q.tags.all())):
                    t = choice(tags)

                    if t not in q.tags.all():
                        q.tags.add(t)
Example #4
0
 def create_tags(self):
     faker = Faker()
     random_tags = faker.words(nb=10, ext_word_list=None)
     for tag in random_tags:
         t = Tag()
         t.title = tag
         t.save()
Example #5
0
    def fill_tags_questions(self):
        tags = [
            'JavaScript', 'Java', 'Django', 'Nginx', 'Gunicorn', 'php', 'Android', 'Jquery', 'Python',
            'HTML', 'CSS', 'ios', 'MySQL', 'Windows', 'Docker'
        ]

        for tag in tags:
            if len(Tag.objects.filter(name=tag)) == 0:
                t = Tag()
                t.name = tag
                t.save()

        number = 10

        tags = Tag.objects.all()

        questions = Question.objects.all()

        for q in questions:
            if len(q.tags.all()) < number:
                for i in range(0, number - len(q.tags.all())):
                    t = choice(tags)

                    if t not in q.tags.all():
                        q.tags.add(t)
                        q.save()
            self.stdout.write('in question [%d] add tags' % q.id)
Example #6
0
async def question_create(request):
    """
    Question form
    """
    session_user = request.user.username
    results = await User.get(username=session_user)
    form = await request.json()
    title = form["title"]
    content = form["content"]
    if request.method == "POST":
        # possible to insert only one tag without error
        if "," in form["tags"] or len((form["tags"]).split()) == 1:
            query = Question(
                title=title,
                slug="-".join(title.lower().split()),
                content=content,
                created=datetime.datetime.now(),
                view=0,
                question_like=0,
                answer_count=0,
                user_id=results.id,
            )
            await query.save()
            tags = []
            # split tags and make sure that is valid tags list without empty
            # space and than insert in db
            valid_tags_list = [i for i in form["tags"].split(",") if i != '']
            for idx, item in enumerate(valid_tags_list):
                tag = Tag(name=item.lower())
                await tag.save()
                tags.append(tag)
                await query.tags.add(tags[idx])
            return RedirectResponse(url="/questions", status_code=303)
        return Response("Tags must be comma-separated", status_code=422)
Example #7
0
    def save(self):
        if self.user is not None:
            question = Question(user=self.user,
                                title=self.cleaned_data["title"],
                                text=self.cleaned_data["question"],
                                snippet=self.cleaned_data["question"][:100])
            question.save()
            #clean() guarantees that cleaned_data has at least one tag
            for tag in self.cleaned_data["tags"]:
                search_tag = Tag.objects.filter(name=tag).last()
                if search_tag:
                    question.tags.add(search_tag)
                else:
                    new_tag = Tag(name=tag)
                    new_tag.save()
                    question.tags.add(new_tag)

            question.save()
            return question
Example #8
0
    def handle(self, *args, **options):
        tags = [
                'javascript', 'java', 'c#', 'php', 'android', 'jquery', 'python',
                'html', 'css', 'c++', 'ios', 'mysql', 'objective-c', 'sql', 'asp.net',
                'ruby-on-rails', 'iphone', 'angularjs', 'regexp'
                ]

        colors = Tag.COLORS

        for tag in tags:
            if len(Tag.objects.filter(title=tag)) == 0:
                t = Tag()

                t.title = tag
                t.color = choice(colors)[0]
                t.save()

        number = int(options['number'])

        tags = Tag.objects.all()

        # for tmp in tags:
        #     self.stdout.write(tmp.title)        

        for question in Question.objects.all():
            self.stdout.write('question [%d]' % question.id)
            if len(question.tags.all()) < number:
                for i in range(number - len(question.tags.all())):
                    tag = choice(tags)
                    if tag not in question.tags.all():
                        question.tags.add(tag)
Example #9
0
    def test_confirm_tags_can_be_selected_unselected(self):
        ''' B: tags enabled/disabled during questions and answers are saved
        and carried over'''
        tag1 = Tag(name='tag1')
        tag2 = Tag(name='tag2')
        tag1.save()
        tag2.save()

        question1 = Question(question="question1")
        question2 = Question(question="question2")
        question1.save()
        question2.save()

        self._login()
Example #10
0
 def handle(self, *args, **options):
     user = User.objects.get(email='*****@*****.**')
     for i in range(1, 5):
         q = Tag(tag_text='tag' + str(i), )
         q.save()
         q = Question(
             author=user,
             question_text='question_text' + str(i),
             header='header' + str(i),
         )
         q.save()
Example #11
0
def create_article(request):
    if request.method == "POST":
        form = ArticleForm(request.POST, request.FILES)
        if form.is_valid():
            #article = form.save()
            article = Article(
                title=form.cleaned_data['title'],
                text=form.cleaned_data['text'],
                author=UserProfile.objects.get(user_id=request.user.id),
            )
            article.save()
            tags = form.cleaned_data['tags'].split(',')
            for t in tags:
                try:
                    tag = Tag.objects.get(name=t)
                except ObjectDoesNotExist:
                    tag = Tag(name=t)
                    tag.save()
                article.tags.add(tag)
            return HttpResponseRedirect(reverse('question', args=[article.id]))
    else:
        form = ArticleForm()
    return render(request, "templates/create_article.html", {"form": form})
Example #12
0
    def test_only_show_questions_with_tag_selected(self):
        ''' Assert that only questions with a given tag are shown '''
        tag1 = Tag(name='tag1')
        tag2 = Tag(name='tag2')
        tag1.save()
        tag2.save()

        question1 = Question(question="question1")
        question2 = Question(question="question2")
        question1.save()
        question2.save()

        self.assertEquals(Question.objects.all().count(), 2)
        self.assertEquals(QuestionTag.objects.all().count(), 0)
        self.assertEquals(UserTag.objects.all().count(), 0)

        self._login()
        # Assert no questions, because user doesn't have any tags selected.
        self._assert_no_questions()
Example #13
0
    def test_tags_created_automatically_for_user(self):
        ''' Assert that a UserTag is created for a user when they hit an endpoint after a Tag has been created. '''
        tag1 = Tag(name='tag1')
        tag2 = Tag(name='tag2')
        tag1.save()
        tag2.save()
        self.assertEquals(UserTag.objects.count(), 0)

        self._login()
        self._assert_no_questions()

        # Assert that QuestionTags were created for this user
        user_tags = UserTag.objects.all()
        self.assertEquals(len(user_tags), 2)
        tag_ids = {user_tag.tag.id for user_tag in user_tags}
        user_ids = {user_tag.user.id for user_tag in user_tags}
        enabled_set = {user_tag.enabled for user_tag in user_tags}
        self.assertEquals(tag_ids, {tag1.id, tag2.id})
        self.assertEquals(user_ids, {self.user1.id})
        self.assertEquals(enabled_set, {False})
Example #14
0
async def question_create(request):
    """
    Question form
    """
    session_user = request.user.username
    results = await User.get(username=session_user)
    data = await request.form()
    form = QuestionForm(data)
    title = form.title.data
    if request.method == "POST" and form.validate():
        # possible to insert only one tag without error
        if "," in form.tags.data or len((form.tags.data).split()) == 1:
            query = Question(
                title=title,
                slug="-".join(title.lower().split()),
                content=form.content.data,
                created=datetime.datetime.now(),
                view=0,
                question_like=0,
                user_id=results.id,
            )
            await query.save()
            tags = []
            # split tags and make sure that is valid tags list without empty
            # space and than insert in db
            valid_tags_list = [i for i in form.tags.data.split(",") if i != '']
            for idx, item in enumerate(valid_tags_list):
                tag = Tag(name=item.lower())
                await tag.save()
                tags.append(tag)
                await query.tags.add(tags[idx])
            return RedirectResponse(url="/questions/?page=1", status_code=302)
        tag_error = "Tags must be comma-separated"
        return templates.TemplateResponse(
            "questions/question_create.html",
            {"request": request, "form": form, "tag_error": tag_error},
        )
    return templates.TemplateResponse(
        "questions/question_create.html", {"request": request, "form": form}
    )
Example #15
0
 def create_tag(self, tagname):
     tag = Tag(name=tagname)
     tag.save()
Example #16
0
def create_tags(n):
    f = Faker()
    for i in range(n):
        tag = Tag(tag_name=f.word())
        tag.save()
    def handle(self, *args, **options):

        print("Adding " + str(options["n_users"][0]) + " users")
        for i in range(0, options["n_users"][0]):
            #generate some random users
            fake_profile = fake.simple_profile()
            profile = Profile(username=fake_profile["name"],
                              email=fake_profile["mail"],
                              login=fake_profile["username"],
                              password=fake.password())
            profile.save()
            print("Saved user with username " + profile.username)

        print("Adding " + str(options["n_tags"][0]) + " tags")
        tags_indexes = list(range(0, len(tags)))
        random.shuffle(tags_indexes)
        for i in range(0, options["n_tags"][0]):
            #add random tags from file
            tag = Tag(name=tags[tags_indexes[i]])
            tag.save()
            print("Saved tag " + tag.name)

        print("Adding " + str(options["n_questions"][0]) + " questions")
        for i in range(0, options["n_questions"][0]):
            #generate some random questoins
            question_text = fake.text(max_nb_chars=400)
            question_snippet = question_text[:97] + "..."
            question_title = fake.sentence()
            question_title = question_title[:(len(question_title) - 1)] + "?"
            tag_objects = list(Tag.objects.all())
            random.shuffle(tag_objects)
            rand_user = Profile.objects.all()[random.randrange(
                0,
                len(Profile.objects.all()) - 1)]

            question = Question(text=question_text,
                                snippet=question_snippet,
                                title=question_title,
                                user=rand_user)
            question.save()
            for i in range(0, random.randrange(2, 4)):
                question.tags.add(tag_objects[i])

            question.save()
            print("Saved question with id " + str(question.id))

        print("Adding " + str(options["n_answers"][0]) + " answers")
        for i in range(0, options["n_answers"][0]):
            #generate some random answers
            answer_text = fake.text(max_nb_chars=250)
            answer_user = Profile.objects.all()[random.randrange(
                0,
                len(Profile.objects.all()) - 1)]
            ans_question = Question.objects.all()[random.randrange(
                0,
                len(Question.objects.all()) - 1)]
            answer_correct = not random.getrandbits(1)
            answer = Answer(text=answer_text,
                            user=answer_user,
                            question=ans_question,
                            correct=answer_correct)
            answer.save()
            print("Saved answer with id " + str(answer.id))

        print("Adding " + str(options["n_qlikes"][0]) + " qlikes")
        for i in range(0, options["n_qlikes"][0]):
            qlike_question = Question.objects.all()[random.randrange(
                0,
                len(Question.objects.all()) - 1)]
            qlike_user = Profile.objects.all()[random.randrange(
                0,
                len(Profile.objects.all()) - 1)]
            while QuestionLike.objects.filter(questionLiked=qlike_question,
                                              user=qlike_user):
                qlike_question = Question.objects.all()[random.randrange(
                    0,
                    len(Question.objects.all()) - 1)]
            like_or_dis = not random.getrandbits(1)
            qlike = QuestionLike(questionLiked=qlike_question,
                                 user=qlike_user,
                                 like_or_dis=like_or_dis)
            qlike.save()
            print("Saved like with userid=" + str(qlike.user.id) +
                  ", questionLiked=" + str(qlike.questionLiked.id))

        print("Adding " + str(options["n_alikes"][0]) + " alikes")
        for i in range(0, options["n_alikes"][0]):
            alike_answer = Answer.objects.all()[random.randrange(
                0,
                len(Answer.objects.all()) - 1)]
            alike_user = Profile.objects.all()[random.randrange(
                0,
                len(Profile.objects.all()) - 1)]
            while AnswerLike.objects.filter(answerLiked=alike_answer,
                                            user=alike_user):
                alike_answer = Answer.objects.all()[random.randrange(
                    0,
                    len(Answer.objects.all()) - 1)]
                alike_user = Profile.objects.all()[random.randrange(
                    0,
                    len(Profile.objects.all()) - 1)]
            like_or_dis = not random.getrandbits(1)
            alike = AnswerLike(answerLiked=alike_answer,
                               user=alike_user,
                               like_or_dis=like_or_dis)
            alike.save()
            print("Saved like with userid=" + str(alike.user.id) +
                  ", questionLiked=" + str(alike.answerLiked.id))
Example #18
0
    def create_tags(tags):
        tag_objs = []
        for tag in tags:
            tag_objs.append(Tag(name=tag))

        Tag.objects.bulk_create(tag_objs)
Example #19
0
    def handle(self, *args, **options):
        # Создание пользователей
        for i in range(0, 30):
            user = User.objects.create_user(
                random.choice([
                    "kiryanenko", "alex", "username", "sidor", "krot",
                    "qwerty", "samsa", 'super', 'hitryy', 'grenom'
                ]) + str(i) + '_' + str(time.time()),
                password="******",
                email=str(i) + '_' + str(time.time()) + random.choice([
                    "*****@*****.**", "*****@*****.**", "*****@*****.**",
                    "*****@*****.**", "*****@*****.**"
                ]))
            user.profile.nick_name = random.choice([
                "kiryanenko", "alex", "username", "sidor", "krot", "qwerty",
                "samsa", 'super', 'hitryy', 'grenom'
            ])
            user.save()
        users = User.objects.all()

        # Создание тегов
        for i in range(0, 30):
            try:
                Tag(name=random.choice([
                    "XML", "JSON", "Python", "C#", "C++", "Ruby",
                    "Ruby on Rails", "Django", "CSS", "HTML", "Perl"
                ])).save()
            except Exception:
                pass
        tags = Tag.objects.all()

        # Создание вопросов
        for i in range(0, 50):
            q = Question(
                title=str(i) + '_' + str(time.time()) + ' ' + random.choice([
                    "Не работает регулярка в PHP в многострочном режиме",
                    "В заданном тексте в конце каждого слова добавить первый символ этого слова",
                    "Замена текста js",
                    "И опять, как всё-таки запустить приложение вне QT?",
                    "jquery и bootstrap", "Плавная смена background-image",
                    "Помогите запустить проект. модуль navigator не видит модуль core. maven",
                    "Не работает функция, в чем может быть ошибка?"
                ]),
                text=random.choice([
                    "Не работает регулярка в PHP в многострочном режиме ",
                    "В заданном тексте в конце каждого слова добавить первый символ этого слова ",
                    "Пытаюсь конвертировать python в exe с помощью pyinstaller, раньше проблем с ним не было... ",
                    "И опять, как всё-таки запустить приложение вне QT? ",
                    "Имеется проблема с получением списка файлов. Функция выполняется. Но на определенном моменте... ",
                    "Есть desktop приложение на java, делаю функцию сохранения... ",
                    "Помогите запустить проект. модуль navigator не видит модуль core. maven ",
                    "Не работает функция, в чем может быть ошибка? "
                ]) * random.randint(1, 20),
                user=random.choice(users),
            )
            q.save()
            for _ in range(0, random.randint(0, 3)):
                q.tags.add(random.choice(tags))
        questions = Question.objects.all()

        # Создание ответов
        for i in range(0, 100):
            Answer(text=random.choice([
                "Похоже здесь неправильно указано имя файла ifstream sf(Students);, а потому файл не открыт. ",
                "В настройках проекта указать, чтобы запуск был с другой формы. ",
                "Вы можете использовать VS для разработки приложений на C++ под андроид. ",
                "У вас остались записи в базе Windows Installer. Первое что вам нужно это выяснить код продукта. ",
                "Имеется проблема с получением списка файлов. Функция выполняется. Но на определенном моменте... ",
                "Решается всё очень просто, но нудно. В реестре вбиваешь в поиск 14 и удаляешь всё, кроме офиса. ",
                "Есть Visual Studio Tools for Apache Cordova - поддерживаются платформы Android, Windows, wp8. ",
                "Есть ограничение на контролы андроидовские, которые можно использовать в виджете... "
            ]) * random.randint(1, 15),
                   question=random.choice(questions),
                   user=random.choice(users)).save()
        answers = Answer.objects.all()

        # Создание лайков вопросов
        for _ in range(0, 200):
            like = QuestionLike(question=random.choice(questions),
                                user=random.choice(users),
                                is_like=bool(random.randint(0, 1)))
            like.save()
            if like.is_like:
                like.question.rating += 1
            else:
                like.question.rating -= 1
            like.question.save()

        # Создание лайков ответов
        for _ in range(0, 200):
            like = AnswerLike(answer=random.choice(answers),
                              user=random.choice(users),
                              is_like=bool(random.randint(0, 1)))
            like.save()
            if like.is_like:
                like.answer.rating += 1
            else:
                like.answer.rating -= 1
            like.answer.save()