Ejemplo n.º 1
0
def test(request, test_id):
    test = Test.objects.filter(pk=test_id).first()
    questions = Question.objects.filter(test=test).order_by('id')

    if request.method == 'POST':
        form = AddQuestionForm(request.POST)
        e_form = EmailStudentForm(request.POST)

        if form.is_valid():
            form.save(commit=False)
            question = Question(
                test=test,
                question=form.cleaned_data['question'],
                answer=form.cleaned_data['answer'],
            )
            question.save()

    else:
        form = AddQuestionForm()
        e_form = EmailStudentForm()

    context = {
        'title': test.test_name,
        'test': test,
        'questions': questions,
        'form': form,
        'e_form': e_form,
        'categories': Category.objects.all(),
        'presets': EmailPreset.objects.all(),
    }
    return render(request, 'main/test.html', context=context)
Ejemplo n.º 2
0
 def handle(self, *args, **options):
     user_id = options['user_id']
     title = ""
     for text_i in options['title']:
         title += str(text_i) + " "
     text = ""
     for text_i in options['text']:
         text += str(text_i) + " "
     name = Question(title=title, user_id=user_id, text=text)
     name.save()
Ejemplo n.º 3
0
 def handle(self, *args, **options):
     user_id = options['user_id']
     title = ""
     for text_i in options['title']:
     	title += str(text_i) +  " " 
     text = ""
     for text_i in options['text']:
     	text += str(text_i) +  " " 
     name = Question(title=title, user_id=user_id, text=text)
     name.save()
Ejemplo n.º 4
0
    def handle(self, *args, **options):
        count = options['n']
        # for answer in Answer.objects.all():
        #     answer.delete()
        # for question in Question.objects.all():
        #     question.delete()
        for q in Question.objects.all():
            q.delete()
        for r in Rates.objects.all():
            r.delete()
        for i in range(0, count):
            number = randint(0,len(titles)-1)
            question = Question()
            question.title = titles[ number ]
            number = randint(0,len(titles)-1)
            question.text = titles[ number ]
            User = get_user_model()
            number = randint(0,User.objects.count()-1)
            question.author = User.objects.all()[number]
            d1 = datetime.strptime('1/1/2014 1:30 PM', '%m/%d/%Y %I:%M %p')
            d2 = datetime.strptime('1/1/2015 4:50 AM', '%m/%d/%Y %I:%M %p')
            question.data = random_date(d1, d2)
            rate = Rates()

            number = randint(0,User.objects.count())
            rate.count = number
            rate.save()
            for i in range(number):
                rate.users.add(User.objects.all()[i])
            question.rate = rate
            number = randint(0,len(tags)-1)
            question.save()

            for i in range(number):
                question.addTag(tags[i])
            for j in range(0,randint(0,10)):
                answer = Answer()
                number = randint(0,len(answers)-1)
                answer.text = answers[number]
                d1 = datetime.strptime('1/1/2014 1:30 PM', '%m/%d/%Y %I:%M %p')
                d2 = datetime.strptime('1/1/2015 4:50 AM', '%m/%d/%Y %I:%M %p')
                answer.data = random_date(d1, d2)
                rate = Rates()
                rate.count = number
                rate.save()
                number = randint(0,User.objects.count())
                for i in range(number):
                    rate.users.add(User.objects.all()[i])
                answer.rate = rate
                number = randint(0,len(titles)-1)
                answer.title = titles[ number ]
                number = randint(0,User.objects.count()-1)
                answer.author = User.objects.all()[number]
                answer.question = question
                answer.save()
Ejemplo n.º 5
0
 def create(self, validated_data):
     validated_data['creator'] = self.context['request'].user
     validated_data['company'] = Company.objects.get(
         company_slug=validated_data['company']['company_slug'])
     validated_data['question_slug'] = utilities.check_slug_available(
         Question, 'question_slug',
         utilities.slug_helper(validated_data['title']) +
         '-{}'.format(validated_data['company'].company_slug))
     question = Question(**validated_data)
     question.save()
     return question
Ejemplo n.º 6
0
def question_create(request):
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        if form.is_valid():
            question = Question(subject=form.cleaned_data['subject'],
                                publication_date=timezone.now())
            question.save()
            return redirect('/questions')
    else:
        form = QuestionForm()
    return render_to_response('question_create.html', {'form': form},
                              context_instance=RequestContext(request))
Ejemplo n.º 7
0
    def test_question_slugify_on_save(self):
        """ Tests that the slug is generated when saving a Question. """
        # Author is a required field in our model.
        # Create a user and save it to the test database.
        user = User()
        user.save()

        # Create and save a new question to the test database.
        question = Question(question_text="Will This Work?", author=user)
        question.save()

        # Make sure the generated slug in Question.save() above
        # matches what we think it should show up.
        self.assertEqual(question.slug, "will-this-work")
Ejemplo n.º 8
0
def ask_question(request):
	if request.POST:
		askform = QuestionForm(request.POST)
		if askform.is_valid():
			new_question = Question(title = askform.cleaned_data['title'], subject = askform.cleaned_data['subject'], content = askform.cleaned_data['content'])
			new_question.save()
			return render(request, 'success.html')
		else:
			context = {'askform': askform}
			return render(request, 'ask_question.html', context)
	else:
		askform = QuestionForm()
		context = {'askform': askform}
		return render(request, 'ask_question.html', context)
Ejemplo n.º 9
0
 def create(self, validated_data):
     validated_data['creator'] = self.context['request'].user
     validated_data['company'] = Company.objects.get(
         company_slug=validated_data['company']['company_slug'])
     validated_data['question_slug'] = utilities.check_slug_available(
         Question, 'question_slug',
         utilities.slug_helper(validated_data['title']) +
         '-{}'.format(validated_data['company'].company_slug))
     question = Question(**validated_data)
     question.save()
     utilities.telegram_notify(
         'New Question: on {}, \n {}'.format(question.company.name,
                                             '#question'), question.id,
         'question', question.title, question.body)
     return question
Ejemplo n.º 10
0
def ask_question(request):
    if request.POST:
        askform = QuestionForm(request.POST)
        if askform.is_valid():
            new_question = Question(title=askform.cleaned_data['title'],
                                    subject=askform.cleaned_data['subject'],
                                    content=askform.cleaned_data['content'])
            new_question.save()
            return render(request, 'success.html')
        else:
            context = {'askform': askform}
            return render(request, 'ask_question.html', context)
    else:
        askform = QuestionForm()
        context = {'askform': askform}
        return render(request, 'ask_question.html', context)
Ejemplo n.º 11
0
def generate_posts(n_posts,
                   text_length_limits=(4, 15),
                   n_tags_limits=(1, 7),
                   tags=None,
                   users=None):
    fake_generator = faker.Faker()
    if tags is None:
        tags = list(Tag.objects.all()[:])
    assert len(tags) >= n_tags_limits[1], \
        f"Not enough tags ({len(tags)}, should be at least" \
        f" {n_tags_limits[1]}) (set in parameters)"

    if users is None:
        users = list(User.objects.all()[:])
    assert len(users) > 0, "Need at least one author to create posts"

    for i in range(n_posts):
        text_length = random.randint(*text_length_limits)
        text = ' '.join(fake_generator.text() for _ in range(text_length))
        n_tags = random.randint(*n_tags_limits)
        post_tags = random.sample(tags, n_tags)
        post_author = random.choice(users)
        title = fake_generator.sentence()
        q = Question(text=text, title=title, author=post_author)
        q.save()
        q.add_tags(post_tags)
        print(f"[{i+1}/{n_posts}] Saved {q} by {post_author}"
              f" with {n_tags} tags and {text_length} texts concatenated")
Ejemplo n.º 12
0
 def search_question_by_keyword(keyword, questioner):
     """
     キーワードに合致するすべての質問のうち、ユーザが投稿した質問を取り出す
     """
     questions = Question.search_by_keyword(keyword=keyword)
     q_list = []
     for q in questions:
         if q.questioner == questioner:
             q_list.append(q)
     return q_list
Ejemplo n.º 13
0
 def question_add(self, contxt, ch1, ch2, ch3, ch4, corr, pnt):
     questid = IDGenerator.generate(Entity.Question)
     Question(id=questid,
              exam_id=self.exam,
              context=contxt,
              choice1=ch1,
              choice2=ch2,
              choice3=ch3,
              choice4=ch4,
              correct=corr,
              point=pnt).save()
Ejemplo n.º 14
0
 def search_replylist_by_keyword(keyword, answerer):
     """
     キーワードに合致するすべての質問のうち、宛先が自分になっているReplyListを取り出す
     """
     questions = Question.search_by_keyword(keyword=keyword)
     reply_lists = ReplyList.objects.filter(answerer=answerer)
     r_list = []
     for q in questions:
         rl = [rl for rl in reply_lists if q.id == rl.question.id]
         r_list.extend(rl)
     return r_list
Ejemplo n.º 15
0
    def setUp(self):
        self.user = Profile.objects.create(
            user=User.objects.create(username="******")
        )

        self.moderator = Profile.objects.create(
            user=User.objects.create(username="******")
        )
        self.moderator.user.is_staff = True
        self.moderator.user.save()

        self.admin = Profile.objects.create(user=User.objects.create(username="******"))
        self.admin.user.is_superuser = True
        self.admin.user.is_staff = True
        self.admin.user.save()

        question = Question(
            title="Test question",
            owner=self.user,
            show_username=True,
            votes=Votes.objects.create(),
        )
        question.save()
        question.tags.add("test-tag")

        Answer(
            text="Test answer",
            parent=question,
            owner=self.user,
            show_username=False,
            votes=Votes.objects.create(),
            is_accepted=False,
        ).save()

        Comment(
            text="Test comment",
            parent_question=question,
            owner=self.user,
            show_username=False,
            votes=Votes.objects.create(),
        ).save()
Ejemplo n.º 16
0
 def post(self, request):
     form = AskForm(request.POST)
     if form.is_valid():
         new_question_id = Question.add_question(form.cleaned_data,
                                                 request.user)
         return HttpResponseRedirect('/question/' + str(new_question_id) +
                                     '/')
     else:
         message = 'Error while adding'
         return render(request, "question/ask.html", {
             "form": form,
             "message": message,
             "trends": Trend.get_trends()
         })
Ejemplo n.º 17
0
def home(request):
    if request.method == 'POST':
        if request.user.is_authenticated:
            By = request.user.username
        else:
            By = 'Newbie'
        Problem = request.POST['problem']
        Description = request.POST['description']
        Tag = request.POST['tag']
        formTime = datetime.datetime.now()
        Time = formTime.strftime("%H:%M:%S  %d-%m-%Y")

        qa = Question(by=By,
                      problem=Problem,
                      description=Description,
                      tag=Tag,
                      time=Time)
        qa.save()
        messages.success(request, 'Succesfully send!')

    qData = Question.objects.all()
    context = {'qdata': qData}
    return render(request, 'Home/home.html', context)
Ejemplo n.º 18
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()
Ejemplo n.º 19
0
def question(self):
    ques1 = Question(question='Why we split data into train and test?',
                     subject=self.subject1,
                     topic=self.topic1,
                     sub_topic=self.subtopic1,
                     qtype=self.qtyp1,
                     difficulties=self.difficulty1,
                     status=2)
    ques2 = Question(
        question=
        'The minsplit parameter to split() specifies the minimum number of splits to make to the input string',
        subject=self.subject2,
        topic=self.topic2,
        sub_topic=self.subtopic2,
        qtype=self.qtyp2,
        difficulties=self.difficulty2,
        status=2)
    ques1.save()
    ques2.save()
    self.question1 = ques1
    self.question2 = ques2
Ejemplo n.º 20
0
 def handle(self):
     for i in range(10):
         user = User.objects.create_user(username='******' + str(i),
                                         password='******' + str(i + 1))
         user.save()
     for i in range(10):
         profile = Profile(user=User.objects.get(username='******' + str(i)),
                           i,
                           date(2005 + i, i + 1, (i + 1) * 2))
         profile.save()
     tags = [
         'django', 'python', 'shell', 'user', 'android', 'net', 'c', 'java',
         'web', 'html'
     ]
     for i in tags:
         tag = Tag(title=i)
         tag.save()
     for i in range(10):
         q = Question(
             title=
             "Cannot to set datetime with input field. Always return DateTime.MinValue",
             text=
             "My programm are supposed to have date filtr and gives article with proper date. But when i input any date in my datetime field my values don't change and are always DateTime.MinValue. Idk why and how i can fix it.",
             is_published=True,
             rating=i,
             author=Profile.objects.get(id=i + 1),
             likes=Profile.objects.get(id=(i + 2) // 2),
             tags=Tag.objects.all()[:i])
     for i in range(10):
         ans = Answer(
             text="Nice question!",
             added_at=date(2019, i + 1, (i + 1) * 2),
             question=Question.objects.get(id=i + 1),
             author=Profile.objects.get(id=(i + 2) // 2),
         )
     for i in range(10):
         ans = Answer(
             text="I don't know!",
             added_at=date(2019, i + 2, i + 3),
             question=Question.objects.get(id=(i + 2) // 2),
             author=Profile.objects.get(id=(i + 3) // 2),
         )
Ejemplo n.º 21
0
    def create(self, validated_data):
        quiz_id = validated_data["quiz_id"]
        type = validated_data['question_type']

        question = Question(question=validated_data['question'],
                            question_type=type,
                            point=validated_data['point'],
                            answer=validated_data['answer'],
                            question_number=validated_data['question_number'])

        if type == "multichoice":
            question.A = validated_data['A']
            question.B = validated_data['B']
            question.C = validated_data['C']
            question.D = validated_data['D']

        question.save()
        quiz = Quiz.objects.filter(id=quiz_id).first()
        quiz.questions.add(question)
        quiz.save()

        return question
Ejemplo n.º 22
0
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()

for qst in q:
    tags = qst.tags
    for i in range(3):
       tags.add(t[rnd.randint(0,10)])
       qst.save()
    
Ejemplo n.º 23
0
 def test_easiness2(self):
   q = Question(text="text", num_marked_right=523, num_marked_wrong=525)
   e = q.easiness();
   q.num_marked_right += 30;
   e2 = q.easiness();
   self.assertGreater(e2, e);
Ejemplo n.º 24
0
from question.models import Tag, Question, Solve
from user.models import User, Career, Team
from message.models import Mail, JoinRequest
from datetime import datetime

T1 = Tag.objects.create(tag_name=Tag.PWN)
T2 = Tag.objects.create(tag_name=Tag.MISC)
T3 = Tag.objects.create(tag_name=Tag.WEB)
T4 = Tag.objects.create(tag_name=Tag.Crypto)
T5 = Tag.objects.create(tag_name=Tag.Reverse)

Q1 = Question(question_tag=T4, question_name="小强的自述", description="小强说了一段话")
Q1.set_flag("NKCTF{HELLO}")
Q1.save()

C1 = Career.objects.create(career_name=Career.PWN)
C2 = Career.objects.create(career_name=Career.MISC)
C3 = Career.objects.create(career_name=Career.WEB)
C4 = Career.objects.create(career_name=Career.Crypto)
C5 = Career.objects.create(career_name=Career.Almighty)

DragonTeam = Team.objects.create(team_name="Dragon",
                                 description="Welcome to Dragon team")
WolfTeam = Team.objects.create(team_name="Tiny Wolf",
                               description="Welcome to tiny wolf team")

User_A = User.objects.create(username="******",
                             score=10,
                             belong=DragonTeam,
                             user_career=C1,
                             is_leader=True,
Ejemplo n.º 25
0
	def handle(sself, *args, **options):
		for i in range(10):
			try:
				user = User.objects.get(username='******'+str(i))
			except User.DoesNotExist:
				user = User.objects.create_user(username='******' + str(i), password='******' + str(i + 1))
				user.is_superuser=False
				user.is_staff=False
				user.save()

		for i in range(10):
			try:
				profile = Profile.objects.get(user=User.objects.get(username='******' + str(i)))
			except Profile.DoesNotExist:
				profile = Profile(user=User.objects.get(username='******' + str(i)), rating=i, birthday=date(2005 + i, i + 1, (i + 1) * 2))
				profile.save()

		tags = ['django', 'python', 'shell', 'user', 'android', 'net', 'c', 'java', 'web', 'html']
		for i in tags:
			try:
				tag = Tag.objects.get(title=i)
			except Tag.DoesNotExist:	
				tag = Tag(title=i)
				tag.save()

		for i in range(10):
			try:
				q = Question.objects.get(title="Cannot to set datetime with input field. Always return DateTime.MinValue" + str(i), 
				text= str(i) + "My programm are supposed to have date filtr and gives article with proper date. But when i input any date in my datetime field my values don't change and are always DateTime.MinValue. Idk why and how i can fix it.",
				is_published=True,
				author=Profile.objects.get(id=i + 1),
				)
			except Question.DoesNotExist:
				q = Question(title="Cannot to set datetime with input field. Always return DateTime.MinValue" + str(i), 
					text=str(i) +"My programm are supposed to have date filtr and gives article with proper date. But when i input any date in my datetime field my values don't change and are always DateTime.MinValue. Idk why and how i can fix it.",
					date_published = datetime.now(),
					is_published=True,
					rating=i,
					author=Profile.objects.get(id=i + 1),
					#likes=likes.set(Profile.objects.get(id=(i + 2)//2)),
					#tags=Tag.objects.get(id=i+1)
					)
				#q.likes.set(Profile.objects.get(id=(i + 2)//2))
				#q.tags.set(Tag.objects.get(id=i+1))
				q.save()
				q.likes.add(Profile.objects.get(id=(i + 2)//2))
				q.tags.add(Tag.objects.get(id=i+1))

		for i in range(10):
			try:
				ans = Answer.objects.get(text="Nice question!",
				added_at = date(2019, i + 1, (i + 1) * 2),
				question=Question.objects.get(id=i + 1),
				author=Profile.objects.get(id=(i + 2)//2),
				)
			except Answer.DoesNotExist:
				ans = Answer(text="Nice question!",
					added_at = date(2019, i + 1, (i + 1) * 2),
					question=Question.objects.get(id=i + 1),
					author=Profile.objects.get(id=(i + 2)//2),
					)
				ans.save()

		for i in range(10):
			try:
				ans = Answer.objects.get(text="I don't know!",
				added_at = date(2019, i + 2, i + 3),
				question=Question.objects.get(id=(i+2)//2),
				author=Profile.objects.get(id=(i+3)//2),
				)
			except Answer.DoesNotExist:
				ans = Answer(text="I don't know!",
					added_at = date(2019, i + 2, i + 3),
					question=Question.objects.get(id=(i+2)//2),
					author=Profile.objects.get(id=(i+3)//2),
					)
				ans.save()
Ejemplo n.º 26
0
from django.core.files import File
from question.models import Answer, Question, AnswerType


def read(qno, filename):
    path = os.path.join(str(qno), filename)
    with open(path, 'r') as fl:
        data = fl.read()
    return data


print('Adding questions')
questions = ''.join(map(str, range(1, 100)))
for ques in questions:
    q = Question()
    q.qno = int(ques)
    try:
        q.title = read(ques, 'title')
        q.text = read(ques, 'text')
        if (ques == '1') or (ques == '2'):
            q.practice = True
        q.save()
    except:
        print('Could not add Q-', ques)
    else:
        try:
            ans = Answer()
            ans.question = q
            ans.infile = File(open(ques + '/inp', 'r'))
            ans.outfile = File(open(ques + '/out', 'r'))
Ejemplo n.º 27
0
django.setup()

from django.core.files import File
from question.models import Answer, Question, AnswerType


def read(qno, filename):
    path = os.path.join(str(qno), filename)
    with open(path, 'r') as fl:
        data = fl.read()
    return data

print('Adding questions')
questions = ''.join(map(str, range(1, 100)))
for ques in questions:
    q = Question()
    q.qno = int(ques)
    try:
        q.title = read(ques, 'title')
        q.text = read(ques, 'text')
        if (ques == '1') or (ques == '2'):
            q.practice = True
        q.save()
    except:
        print('Could not add Q-', ques)
    else:
        try:
            ans = Answer()
            ans.question = q
            ans.infile = File(open(ques + '/inp', 'r'))
            ans.outfile = File(open(ques + '/out', 'r'))
Ejemplo n.º 28
0
def question_edit(request, id=None, msg=None):
    """
    質問ページ
    """

    # edit
    # 質問の編集機能は今は下書きの場合のみ使う
    if id:
        q = get_object_or_404(Question, pk=id)
        # user check
        if q.questioner != request.user:
            return top_default(request, msg=m.INFO_INVALID_ACCESS)
    # new
    else:
        q = Question()

    # edit
    if request.method == 'POST':
        form = QuestionEditForm(request.POST, instance=q)

        if form.is_valid():
            # 質問を保存
            q = form.save(commit=False)
            q.update(questioner=request.user, draft=form.cleaned_data['draft'])
            if q.draft:
                return top_default(request, msg=m.INFO_QUESTION_SAVE_OK)

            # 質問の宛先(複数)を生成
            div_list = form.cleaned_data['destination']
            for div in div_list:
                QuestionDestination.objects.create(question=q, tag=div)

            # ランダムに質問者を選んでReplyListを生成
            qa_manager = QAManager()
            r_list = qa_manager.make_reply_list(q, qa_manager.reply_list_update_random_except)

            if r_list is None:
                q.delete()
                msg = m.INFO_NO_DESTINATION
                return render_to_response('question/question_edit.html',
                                          {'form': form, 'id': id, 'msg': msg},
                                          context_instance=RequestContext(request))
            else:
                r_list.save()

            # 選択されたタグから、新規にQuestionTagを生成
            q_tags = form.cleaned_data['tag']
            for q_tag in q_tags:
                QuestionTag.objects.create(tag=q_tag, question=q)

            # 追加されたタグ名が新規に追加されたタグだったら生成
            tag_name = Tag.get_all_tags_name()
            tag_added_name = form.cleaned_data['tag_added']
            if tag_added_name != "" and tag_added_name not in tag_name:
                QuestionTag.objects.create(tag=Tag.objects.create(name=tag_added_name), question=q)

            return top_default(request, msg=m.INFO_QUESTION_SEND_OK)
        pass
    # new
    else:
        form = QuestionEditForm(instance=q, initial={'time_limit': datetime.timedelta(minutes=1)})

    return render_to_response('question/question_edit.html',
                              {'form': form, 'id': id},
                              context_instance=RequestContext(request))
Ejemplo n.º 29
0
 def test_easiness(self):
   q = Question(text="test",num_marked_right=5,num_marked_wrong=3);
   e = q.easiness();
   q.num_marked_wrong += 5;
   e2 = q.easiness();
   self.assertGreater(e, e2);
Ejemplo n.º 30
0
    def handle(self, *args, **options):
        if options["flush"]:
            call_command("flush", "--noinput")

        fake = Faker("hu_HU")
        users = []

        if not User.objects.filter(username="******").exists():
            admin = User()
            admin.username = "******"
            admin.is_superuser = True
            admin.is_staff = True
            admin.first_name = "Admin"
            admin.last_name = "Adminsson"
            admin.set_password("admin")
            admin.save()
            Profile.objects.create(user=User.objects.get(username="******"))
        users.append("admin")

        if not User.objects.filter(username="******").exists():
            User.objects.create(username="******",
                                is_staff=True,
                                first_name="Mod",
                                last_name="Mod")
            Profile.objects.create(user=User.objects.get(username="******"))
        users.append("mod")

        if not User.objects.filter(username="******").exists():
            User.objects.create(username="******",
                                first_name="User",
                                last_name="User")
            Profile.objects.create(user=User.objects.get(username="******"))
        users.append("user")

        # Accounts
        for i in range(random.choice(range(3, 9))):
            # Users
            fakedata = fake.simple_profile()
            u = User()
            u.username = fakedata["username"]
            name = fakedata["name"].split(" ")
            u.first_name = name[0]
            u.last_name = name[1]
            u.save()
            # Profiles
            Profile.objects.create(user=u)
            users.append(u.username)

        # Tags
        tag_choices = []
        for t in range(random.choice(range(5, 11))):
            tag_choices.append(fake.word())

        # Questions
        for i in range(random.choice(range(3, 11))):
            ov_q = self.generate_owner_votes(users)
            q = Question()
            q.title = fake.text(max_nb_chars=50)
            q.text = fake.paragraph(nb_sentences=4)
            q.owner = Profile.objects.get(user__username=ov_q["owner"])
            q.show_username = bool(random.getrandbits(1))
            q.votes = ov_q["votes"]
            q.created_at = datetime.datetime.now()
            q.save()
            for t in random.sample(tag_choices,
                                   random.randint(0, len(tag_choices))):
                q.tags.add(t)
            # Comments
            for j in range(random.choice(range(0, 4))):
                ov_cq = self.generate_owner_votes(users)
                Comment.objects.create(
                    parent_question=q,
                    text=fake.paragraph(nb_sentences=4),
                    owner=Profile.objects.get(user__username=ov_cq["owner"]),
                    show_username=bool(random.getrandbits(1)),
                    votes=ov_cq["votes"],
                )
            # Answers
            accepted_answer = -1
            answer_count = random.choice(range(0, 6))
            has_accepted = bool(random.getrandbits(1))
            if has_accepted and answer_count > 0:
                accepted_answer = random.choice(range(answer_count))
            for k in range(answer_count):
                ov_a = self.generate_owner_votes(users)
                a = Answer()
                a.text = fake.paragraph(nb_sentences=4)
                a.owner = Profile.objects.get(user__username=ov_a["owner"])
                a.show_username = bool(random.getrandbits(1))
                if k == accepted_answer:
                    a.is_accepted = True
                else:
                    a.is_accepted = False
                a.votes = ov_a["votes"]
                a.parent = q
                a.save()
                # Comments to answers
                for l in range(random.choice(range(0, 4))):
                    ov_ca = self.generate_owner_votes(users)
                    Comment.objects.create(
                        parent_answer=a,
                        text=fake.paragraph(nb_sentences=4),
                        owner=Profile.objects.get(
                            user__username=ov_ca["owner"]),
                        show_username=bool(random.getrandbits(1)),
                        votes=ov_ca["votes"],
                    )
Ejemplo n.º 31
0
def question_edit(request, id=None, msg=None):
    """
    質問ページ
    """

    # edit
    if id:
        q = get_object_or_404(Question, pk=id)
        # user check
        if q.questioner != request.user:
            print("不正なアクセスです!")
            return redirect('dotchain:top')
    # new
    else:
        q = Question()

    # edit
    if request.method == 'POST':
        form = QuestionEditForm(request.POST, instance=q)

        # 完了がおされたら
        if form.is_valid():
            # 質問を保存
            q = form.save(commit=False)
            q.questioner = request.user
            q.draft = form.cleaned_data['draft']
            q.save()

            div_list = form.cleaned_data['destination']
            for div in div_list:
                d = QuestionDestination()
                d.question = q
                d.tag = div
                d.save()

            # ランダムに質問者を選んでからReplyListを生成して保存
            qa_manager = QAManager()
            r_list = qa_manager.make_reply_list(q, qa_manager.reply_list_update_random_except)

            if r_list is None:
                q.delete()

                msg = '宛先ユーザが見つかりませんでした。入力された質問は消去されます。\n'
                msg += '次の原因が考えられます。\n'
                msg += '・送信先にユーザがいない\n'
                msg += '・送信先に1日以内にログインしたユーザがいない\n'
                msg += '・送信先に受信拒否のユーザしかいない'

                return render_to_response('question/question_edit.html',
                                          {'form': form, 'id': id, 'msg': msg},
                                          context_instance=RequestContext(request))
            else:
                r_list.save()

            # 選択されたタグから、新規にQuestionTagを生成して保存
            q_tags = form.cleaned_data['tag']
            for q_tag in q_tags:
                qt = QuestionTag()
                qt.tag = q_tag
                qt.question = q
                qt.save()

            # 追加されたタグ名から、新規にTagとQuestionTagを生成して保存
            tag_added_name = form.cleaned_data['tag_added']
            tags = Tag.objects.all()
            tag_name = [t.name for t in tags]
            if tag_added_name != "" and tag_added_name not in tag_name:  # 新規に追加されたタグだったら保存
                t = Tag()
                t.name = tag_added_name
                t.save()
                qt = QuestionTag()
                qt.tag = t
                qt.question = q
                qt.save()

            return redirect('dotchain:top')
        pass
    # new
    else:
        form = QuestionEditForm(instance=q, initial={'time_limit': datetime.timedelta(minutes=1)})

    return render_to_response('question/question_edit.html',
                              {'form': form, 'id': id},
                              context_instance=RequestContext(request))
Ejemplo n.º 32
0
    def handle(self, *args, **options):
        count = options['n']
        # for answer in Answer.objects.all():
        #     answer.delete()
        # for question in Question.objects.all():
        #     question.delete()
        for q in Question.objects.all():
            q.delete()
        for r in Rates.objects.all():
            r.delete()
        for i in range(0, count):
            number = randint(0, len(titles) - 1)
            question = Question()
            question.title = titles[number]
            number = randint(0, len(titles) - 1)
            question.text = titles[number]
            User = get_user_model()
            number = randint(0, User.objects.count() - 1)
            question.author = User.objects.all()[number]
            d1 = datetime.strptime('1/1/2014 1:30 PM', '%m/%d/%Y %I:%M %p')
            d2 = datetime.strptime('1/1/2015 4:50 AM', '%m/%d/%Y %I:%M %p')
            question.data = random_date(d1, d2)
            rate = Rates()

            number = randint(0, User.objects.count())
            rate.count = number
            rate.save()
            for i in range(number):
                rate.users.add(User.objects.all()[i])
            question.rate = rate
            number = randint(0, len(tags) - 1)
            question.save()

            for i in range(number):
                question.addTag(tags[i])
            for j in range(0, randint(0, 10)):
                answer = Answer()
                number = randint(0, len(answers) - 1)
                answer.text = answers[number]
                d1 = datetime.strptime('1/1/2014 1:30 PM', '%m/%d/%Y %I:%M %p')
                d2 = datetime.strptime('1/1/2015 4:50 AM', '%m/%d/%Y %I:%M %p')
                answer.data = random_date(d1, d2)
                rate = Rates()
                rate.count = number
                rate.save()
                number = randint(0, User.objects.count())
                for i in range(number):
                    rate.users.add(User.objects.all()[i])
                answer.rate = rate
                number = randint(0, len(titles) - 1)
                answer.title = titles[number]
                number = randint(0, User.objects.count() - 1)
                answer.author = User.objects.all()[number]
                answer.question = question
                answer.save()
Ejemplo n.º 33
0
 def test_num_answered(self):
   nr = 12323;
   nw = 94246;
   q = Question(num_marked_right=nr, num_marked_wrong=nw);
   na = q.num_answered();
   self.assertEqual(na, nr + nw);