def setUp(self): # create an organisation user = User(username='******') user.save() org = Organisation(name='test_org') org.user = user org.save() # create three questions self.q1 = Question(question='What is your name?', organisation=org) self.q1.save() # create a candidate self.candidate = Candidate(name='Terry', participating=True, popit_id=1234) self.candidate.save() # post-save hook on candidate will automatically assign q1 q2 = Question(question='What is your quest?', organisation=org) q2.save() q3 = Question(question='What is your favourite colour?', organisation=org) q3.save() # assign 1 question to the candidate self.answer = Answer.objects.get(question=self.q1, candidate=self.candidate)
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()
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)
def test_get_absolute_url(self): question = Question(title='test_title', question='asasdasdas', owner_id=1) question.save() resp = self.client.get(question.get_absolute_url()) self.assertEquals(resp.status_code, 200)
def doimport(self, data): from django.contrib.auth.models import User from questions.models import Question, Answer from tagging.models import Tag try: question = Question() question.content = data['question'] question.tags = data['tags'] question.author = User.objects.get( pk=0) #FIXME: System smrtr user: use constant? question.save() # Save to allow m2m # Create correct answer c = Answer() c.content = data['correct'] c.is_correct = True c.question = question c.save() # Save incorrect answers data['incorrect'] = filter(lambda x: len(x) > 0, data['incorrect']) # Remove empty items for incorrect in data['incorrect']: ic = Answer() ic.content = incorrect ic.is_correct = False ic.question = question ic.save() except: print "Error importing:" + data['question']
def submit_question(request): # If this is a POST request then process form data if request.method == 'POST': # Grab the question from the request form = SubmitQuestionForm(request.POST) # Check if the question is actually valid if form.is_valid(): # If it is, then create a new PrivateQuestion data new_question = Question(subject=form.cleaned_data['subject'], content=form.cleaned_data['content'], post_date=datetime.date.today()) # If op choses to give us his email, record it if form.data['email']: new_question.op_email = form.cleaned_data['email'] # Query the new question to the database new_question.save() return HttpResponseRedirect(reverse('submit-success')) # If this is a GET request then give out the new form else: form = SubmitQuestionForm() context = { 'form': form, } return render(request, 'questions/submit_question.html', context)
def board(request, username): # TODO: refactor into a class based view try: profile = Profile.objects.get(user__username=username) except Profile.DoesNotExist: messages.warning(request, f"No user found with username: {username}") return HttpResponse(f"No user found with username: {username}") if request.method == 'POST' and request.user.is_authenticated: form = PostQuestionForm(request.POST) if form.is_valid(): q = Question(asked_by=request.user if not form.cleaned_data.get('is_anonymous') else None, asked_to=profile.user, content=form.cleaned_data.get('question_text')) q.save() messages.success(request, 'Question posted successfully!') elif request.method == 'POST' and not request.user.is_authenticated: messages.warning(request, 'Log in to post a question.') return redirect('/login/') form = PostQuestionForm() questions = profile.user.get_public_questions() paginator = Paginator(questions, 5) questions_page = paginator.get_page(request.GET.get('page')) return render( request, 'core/board.html', { 'question_max_length': 512, 'profile': profile, 'questions_page': questions_page, 'form': form })
def fill_questions(self): fake = Factory.create() starts = ( 'How do I Sort a Multidimensional', 'What is Max?', 'SQL Server' ) for i in range(0, 40): q = Question() q.title = fake.sentence(nb_words=randint(2, 4), variable_nb_words=True) q.text = u"%s %s %s" % ( choice(starts), os.linesep, fake.paragraph(nb_sentences=randint(1, 4), variable_nb_sentences=True), ) q.author = Profile.objects.first() q.rating = randint(0, 1500) q.id = i q.save() self.stdout.write('add question [%d]' % (q.id))
def test_form_should_post_proper_data_via_signal(self): """ test signal sending message if added a comment """ mock_handler = MagicMock() user = User.objects.create_user(username='******', email='*****@*****.**', password='******') user.save() question = Question(title='test_title', question='asasdasdas', owner_id=1) question.save() answer = Answer(answer_text='some_text', answers_question=question) answer.save() signals.post_save.connect(mock_handler, sender=Answer) signals.post_save.send(sender=Answer, instance=question, answer=answer.answer_text) # handler.assert_called_once_with( # signal=signals.post_save.send, # sender=Answer, # instance=question, # answer=answer.answer_text) self.assertEquals(mock_handler.call_count, 1)
def handle(self, *args, **options): users = list(User.objects.all()) for i in range(10): t = Topic() t.name = u'Topic Name {}'.format(i) t.description = u'Topic Description {}'.format(i) t.save() topics = list(Topic.objects.all()) for j in range(100): q = Question() q.author = random.choice(users) q.title = u'title {}'.format(j) q.text = u'text {}'.format(j) q.pub_date = datetime.datetime.now() q.is_published = True q.save() q.topics = random.sample(topics, random.randint(1, 6)) questions = list(Question.objects.all()) for k in range(100): c = Comment() c.author = random.choice(users) c.question = random.choice(questions) c.text = u'text {}'.format(k) c.pub_date = datetime.datetime.now() c.save()
def new_question(request, politician_id=None): user = request.user request_info = get_request_information(request) question = Question( created_by=user, user_ip=request_info.client_ip, user_agent=request_info.client_user_agent, user_country=request_info.client_country ) selected_politician = PoliticianInfo.active.filter(id=politician_id).first() if politician_id else None initial = {} if selected_politician: initial['politician'] = selected_politician new_question_form = NewQuestionForm(instance=question, initial=initial) success = None if request.method == 'POST': success = False new_question_form = NewQuestionForm(request.POST, instance=question) if new_question_form.is_valid(): with reversion.create_revision(): new_question_form.save() return redirect('question', question_id=question.id) return render(request, 'questions/new-question.html', { 'new_question_form': new_question_form, 'success': success })
def question_create(request, name, content, author, categories=None, is_archive=None): if request.method == 'POST': if is_archive is None: archive = False else: archive = is_archive category_list = [] if categories is not None: categories = Category.objects.all() for category in categories: category_list.append(categories.filter(name=category)) user = User.objects.get(username=author) question = Question(name=name, content=content, author=user, is_archive=archive, categories=category_list) question.save() return {"result": "success"} return {"error": "not post"}
def create_or_modify(topic_name, question, answer, user): """ Creates or modifies a topic based if we have topics with the name entered and the user is the creator. """ query_ids = topics_by_id(topic_name) topic_com = None for topic_id in query_ids: topic = Topic.objects.get(id=topic_id) if topic.creator == user: topic_com = topic break if not topic_com: topic_to_add = Topic() topic_to_add.name = parsing.scrub_name(topic_name) topic_to_add.color = random_color() topic_to_add.creator = user topic_to_add.created_flag = False topic_to_add.save() topic_com = topic_to_add # In case the user wants to add questions to an existing topic. question_to_add = Question() question_to_add.topic = topic_com question_to_add.question = markdown.markdown(question) question_to_add.answer = markdown.markdown(answer) question_to_add.added_flag = False question_to_add.save() return topic_com
def post(self, request): title = request.POST['title'] details = request.POST['details'].replace("'", ''') author = request.user question = Question(title=title, question_details=details) try: question.anonymous = request.POST['anonymous'] except: pass # if request.POST['anonymous']: # question.anonymous = True question.author = author question.save() if question.anonymous: AnonymousQuestionsWriters(question=question, user=request.user).save() write_profile = author.profile write_profile.no_of_questions += 1 write_profile.save() follow_question.delay(question.id, request.user.id) return redirect('/questions/' + str(question.slug))
def q_and_a_creation(q_body, a_body): length = len(Question.objects.all()) q_new = Question(body=q_body, address=(length + 1)) a_new = Answer(body=a_body, address=(length + 1)) add_new_data_to_db_files(q_new, a_new) q_new.save() a_new.save() return [q_new.address, a_new.address]
def test_notification_created(self): """Creating a new question auto-watches it for answers.""" u = User.objects.get(pk=118533) q = Question(creator=u, title='foo', content='bar') q.save() assert QuestionReplyEvent.is_notifying(u, q)
def _create_tags_and_questions(self): for i in range(len(self.titles)): current_question = Question(id=i, title=self.titles[i], user_id=0, details=self.descriptions[i]) current_question.save() tag = Tag(id=i, name=self.tags[i]) tag.save()
def save(self, user): question = Question( title=self.cleaned_data['title'], text=self.cleaned_data['text'], author=Profile.objects.filter(user=user).first(), ) question.save() return question._get_pk_val()
def setUp(self): super(TestQuestionMetadata, self).setUp() # add a new Question to test with question = Question(title='Test Question', content='Lorem Ipsum Dolor', creator_id=1) question.save() self.question = question
def handle(self, *args, **options): questions = [ 'what is the capital of India', 'what is the capital of Telangana', 'what is the capital of Pakisthan' ] for each in range(100): title = random.choice(questions) data = Question.objects.bulk_create([Question(title=title)]) print("{} questions inserted Succesfully!".format(each))
def respond_question(request, pk_meeting, pk_quiz): meeting = get_object_or_404(Meeting, pk=pk_meeting) quiz = get_object_or_404(Quiz, pk=pk_quiz) list_questions = quiz.question_questionnaires.all() BaseQuestionFormSet = formset_factory(QuestionCompleteForm, extra=len(list_questions)) options = {'NÃO', 'SIM'} cont = 1 questions = [] if request.method == 'POST' or request.method == 'post': question_form = BaseQuestionFormSet(request.POST) if question_form.is_valid(): for auxQuestion in list_questions: questions.append(auxQuestion) for aux in range(len(list_questions)): question = Question() question_id = request.POST.get('question_' + str(cont)) answer = request.POST.get('answer_' + str(question_id)) question_remove = Question.objects.get(id=questions[aux].id) cont += 1 question.question = questions[aux].question question.answer = answer if answer != None: quiz.question_questionnaires.remove(question_remove) question_remove.delete() question.save() quiz.question_questionnaires.add(question) questions_json(pk_quiz) messages.success(request, 'Questionário Respondido Com Sucesso!') return redirect('meeting_show', pk=meeting.id) else: question_form = BaseQuestionFormSet() return render( request, 'questions/respond_question.html', { 'formset': question_form, 'meeting': meeting, 'quiz': quiz, 'list_questions': list_questions, 'options': options })
def setUp(self): user = User(username='******') user.save() o1 = Organisation(name='Organisation 1') o1.user = user o1.save() user = User(username='******') user.save() o2 = Organisation(name='Organisation 2') o2.user = user o2.save() c1 = Candidate(popit_id=1235, name='Bob', contact_address='*****@*****.**', participating=True) c1.save() self.candidate = c1 q1 = Question( organisation=o1, question='What is your name?', type='text', ) q1.save() q2 = Question( organisation=o2, question='What is your quest?', type='text', ) q2.save() a1 = Answer(candidate=c1, question=q1, completed=True, completed_timestamp=datetime.datetime( 2015, 1, 1, tzinfo=timezone.get_current_timezone())) a1.save() self.a1 = a1 a2 = Answer(candidate=c1, question=q2, completed=False) a2.save() self.a2 = a2
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()
def create_questions(questions, poll_id): for question in questions: new_question = Question(title=question.title, poll=Poll.objects.get(pk=poll_id), answer=question.answer) new_question.save() for choice in question.choices: new_choice = Choice(title=choice, question=new_question) new_choice.save()
def test_no_inactive_users(self): """Ensure that inactive users' questions don't appear in the feed.""" u = User.objects.get(pk=118533) u.is_active = False u.save() q = Question(title='Test Question', content='Lorem Ipsum Dolor', creator_id=118533) q.save() assert q.id not in [x.id for x in QuestionsFeed().items()]
def setUp(self): self.question_catalogue = QuestionCatalogue(pk=1, catalogue_scope='private', catalogue_name='tests') self.question_catalogue.save() question = Question(pk=1, question_text="text", question_catalogue=self.question_catalogue) question.save()
def setUp(self): self.user1 = User(email='*****@*****.**', username='******', password='******', is_active=True) self.user1.save() self.user2 = User(email='*****@*****.**', username='******', password='******', is_active=True) self.user2.save() self.u1_q1 = Question(content='question 1 to user1?', asked_by=self.user2, asked_to=self.user1) self.u1_q1.save() self.u2_q1 = Question(content='question 1 to user2?', asked_by=self.user1, asked_to=self.user2) self.u2_q1.save()
def question(**kwargs): defaults = dict(title=str(datetime.now()), content='', created=datetime.now(), num_answers=0, is_locked=0) defaults.update(kwargs) if 'creator' not in kwargs and 'creator_id' not in kwargs: defaults['creator'] = user(save=True) return Question(**defaults)
def setUp(self): '''Set up the test and category infrastructure.''' #Course Instantiation self.course = Course(name="testing course", slug="testing-course") self.course.save() #Course Section Instantiation self.coursesection = CourseSection(name="Section 1", course=self.course) self.coursesection.save() #Category Instantiation self.category = Category( name="Category 1 for testing course", slug="cat-1-testing-course", section=self.coursesection, ) self.category.save() #SubCategory Instantiation self.subcategory = SubCategory( name="SubCategory 1 for testing course", slug="subcategory-1-testing-course", category=self.category, ) self.subcategory.save() #User creation self.user = MyUser.objects.create_test_user( username="******", email="*****@*****.**", password="******", ) self.user2 = MyUser.objects.create_test_user( username="******", email="*****@*****.**", password="******", ) #Question creation self.question = Question( course=self.course, section=self.coursesection, category=self.category, subcategory=self.subcategory, question_text="Here is an example question.", option_A="Here is option A.", option_B="Here is option B.", answer_letter="A", answer_explanation="Here is an example explanation.", index=1, ) self.question.save()
def 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()