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)
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")
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()
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()
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()
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
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))
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
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")
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
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)
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()
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), )
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()
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
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)
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()
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()
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'))
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,
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"], )