• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python models.Question类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中models.Question的典型用法代码示例。如果您正苦于以下问题:Python Question类的具体用法?Python Question怎么用?Python Question使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Question类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: upload_new_question

def upload_new_question(question_source, question, tags):
    new_question = Question(question = question, question_source=question_source)
    new_question.save()
    tags_final = []

    for tag in tags:
        try:
            search_tag = Tag.objects.get(tag=tag)
            tags_final.append(search_tag)
            continue
        except Tag.DoesNotExist:
            new_tag = Tag(tag=tag)
            new_tag.save()
            tags_final.append(new_tag)
            continue
        continue
    
    for tag in tags_final:
        print tag.tag

    for tag in tags_final:
        tag.questions.append(new_question)
        tag.save()
        continue

    return new_question.id
开发者ID:YNCHacks,项目名称:Qanda,代码行数:26,代码来源:views.py


示例2: create_question

def create_question(request):
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST']) 
    
    recording_url = request.POST['RecordingUrl']
    recording_url.replace('2010-04-01', '2008-08-01')
    to_number = request.POST['To']
    from_number = request.POST['From']
    
    number = PhoneNumber.objects.get(number=to_number)
    language = number.language
    
    log.debug(recording_url)
    
    q = Question(to_number=to_number,
                 from_number=from_number,
                 language=language, 
                 recording_url=recording_url)
    q.save()

    log.debug('Question Created: %s' % q)

    r = twiml.Response()
    r.hangup()
    
    return HttpResponse(r)
开发者ID:robboyle,项目名称:asesor,代码行数:26,代码来源:views.py


示例3: get

    def get( self ):
        q = get_approving_question()

        if q == None or q.question == None:
            q = get_unapproved_question()

        if q == None:
            q = Question()
            
        """
        q_submitters = get_questions_with_submitters()
        submitters   = []
        for s in q_submitters:
            if s.submitter and not s.submitter in submitters:
                submitters.append( s.submitter )
        """

        logging.info('Question: %s %s %s' % (q.question, q.category, q.answer))

        q.state = 'approving'
        q.put()

        template_values = { 
            'CSS_FILE' : 'admin',
            'JS_FILE' : '',
            'q' : q,
            'num_not_approved' : get_unapproved_question_count()
        }
        
        self.response.out.write( template.render( 'templates/admin.html', template_values ) )
开发者ID:BarbaraEMac,项目名称:TrivBot,代码行数:30,代码来源:admin.py


示例4: new_question

def new_question():
    """Creates a new question"""
    form = QuestionForm()
    if request.method == 'POST' and form.validate_on_submit():
        question = Question(
            content=form.content.data,
            added_by=users.get_current_user(),
            location=get_location(form.location.data)
        )
        try:
            question.put()
            question_id = question.key.id()

            create_nearby_question(question_id)

            flash(u'Question %s successfully saved.' % question_id, 'success')
            add_question_to_search_index(question)


            return redirect(url_for('list_questions_for_user'))
        except CapabilityDisabledError:
            flash(u'App Engine Datastore is currently in read-only mode.', 'info')
            return redirect(url_for('list_questions_for_user'))
    else:
        flash_errors(form)
        return redirect(url_for('list_questions_for_user'))
开发者ID:ahbuntu,项目名称:ece1779,代码行数:26,代码来源:views.py


示例5: get

    def get(self):
        numADQuestions = Question.gql('WHERE product = :1', 'ADSync').count()
        numSPQuestions = Question.gql('WHERE product = :1', 'SharePoint Web Part').count()
        numSSOQuestions = Question.gql('WHERE product = :1', 'SSO').count()

        values = { 'numADQuestions': numADQuestions, 'numSPQuestions': numSPQuestions, 'numSSOQuestions': numSSOQuestions }
        self.response.out.write(template.render('templates/index.html', values))
开发者ID:nmccarthy,项目名称:Yammer-Integration-Questionnaire,代码行数:7,代码来源:questionnaire.py


示例6: list_questions_for_user

def list_questions_for_user():
    """Lists all questions posted by a user"""

    form = QuestionForm()
    search_form = QuestionSearchForm()
    user = users.get_current_user()
    login_url = users.create_login_url(url_for('home'))

    query_string = request.query_string
    latitude = request.args.get('lat')
    longitude = request.args.get('lon')
    radius = request.args.get('r')

    # If searching w/ params (GET)
    if request.method == 'GET' and all(v is not None for v in (latitude, longitude, radius)):
        q = "distance(location, geopoint(%f, %f)) <= %f" % (float(latitude), float(longitude), float(radius))
        index = search.Index(name="myQuestions")
        results = index.search(q)

        # TODO: replace this with a proper .query
        questions = [Question.get_by_id(long(r.doc_id)) for r in results]
        questions = filter(None, questions) # filter deleted questions
        if questions:
            questions = sorted(questions, key=lambda question: question.timestamp)
    else:
        questions = Question.all_for(user)

    channel_token = safe_channel_create(all_user_questions_answers_channel_id(user))
    return render_template('list_questions_for_user.html', questions=questions, form=form, user=user, login_url=login_url, search_form=search_form, channel_token=channel_token)
开发者ID:ahbuntu,项目名称:ece1779,代码行数:29,代码来源:views.py


示例7: ask_display

def ask_display(request):
        if not request.user.is_authenticated():
            raise PermissionDenied

        if request.method == 'POST':

            request_title = request.POST.get('title')
            request_text = request.POST.get('text')
            request_tags = request.POST.get('tags')
            
            if request_title == '' or request_text == '':
                return render(request, 'ask.html', {'page_title': 'New Question', 'errors': '1'})
            
            new_question = Question(title = request_title, 
                date = datetime.datetime.now(), 
                author = UserProfile.objects.get(user_account = request.user),
                text = request_text)
            
            new_question.save()
            
            for tag_str in request_tags.split(','):
                if Tag.objects.filter(name = tag_str).exists():
                    tag = Tag.objects.get(name = tag_str)
                    new_question.tags.add(tag)
                else:
                    new_tag = Tag(name = tag_str)
                    new_tag.save()
                    new_question.tags.add(new_tag)
            
            return HttpResponseRedirect('/question/{}'.format(new_question.id))
            
        return render(request, 'ask.html', {'page_title': 'New Question', 'errors': '0'})
开发者ID:TimeEscaper,项目名称:Ask_AI_TP-mail.ru,代码行数:32,代码来源:views.py


示例8: ask

def ask(request):
    if request.method == 'POST':
        form = QuestionForm(request.POST)
        if form.is_valid():
            q = Question(
                created_by=request.user,
                author=request.user,
                category=form.cleaned_data['category'],
                title=form.cleaned_data['title'],
                text=form.cleaned_data['text'],
            )
            q.save()

            return redirect(reverse('support:question', args=(q.id,)))
    else:
        form = QuestionForm()

    c = {
        'form': form,
        'search_form': SearchForm(),

        'categories': p.CATEGORIES,

        'title': _("Ask a question"),
        'site_title': g.SITE_TITLE,
    }

    return render(request, 'support/ask.html', c)
开发者ID:rokj,项目名称:sellout,代码行数:28,代码来源:views.py


示例9: askquestion

def askquestion(request):
    """提问模板"""
    name =request.session.get('name')
    if request.method == "POST" and request.is_ajax():

        form = QuestionForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            title = data['title']
            text = data['text']
            qtype = data['q_type'].lower()
            user = User.objects.get(name=name.split()[0])
            try:
                questiontype = QuestionType.objects.get(name=qtype)
            except QuestionType.DoesNotExist:
                questiontype = QuestionType(name=qtype)
                questiontype.save()

            question = Question(user=user, title=title, text=text, q_type=questiontype)
            question.save()


            # return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
            return JsonResponse({'status':'ok'})
        else:
            # return HttpResponse(request.POST.get('title'))
            return render(request, 'askquestion.html')
    if name:
        return render(request,'askquestion.html',{'QuestionForm':QuestionForm, 'name':name.split()})
    else:
        return HttpResponseRedirect("/")
开发者ID:NaomiGeng,项目名称:iforj,代码行数:31,代码来源:views.py


示例10: save_scratch

def save_scratch(kind='', subject='', theme='', text='', answers=[]):
	'''
	save question from scratch to database
	'''
	q = Question(kind=kind, subject=subject, theme=theme, text=text, answers=answers)
	q.save()
	return True
开发者ID:Samael500,项目名称:owl,代码行数:7,代码来源:question_helper.py


示例11: create_test_backup

def create_test_backup(request):
    test_obj = json.loads(request.body)
    test = Test()
    #import pdb; pdb.set_trace()
    if request.user.is_authenticated():
        owner = User_Profile.objects.filter(user = request.user)
        test.owner = owner[0]
        test.test_name = test_obj['PRE_TEST']['test_name']
        #test.subject = test_obj['PRE_TEST'].subject
        #test.target_exam = test_obj['PRE_TEST'].target_exam
        #test.topics = test_obj['PRE_TEST'].topics_included
        test.total_time = test_obj['PRE_TEST']['total_time']
        test.pass_criteria = test_obj['PRE_TEST']['pass_criteria']
        test.assoicated_class = Class.objects.get(pk=test_obj['CLASS_INFO'])
        test.save()
        try:
            for item in test_obj['QUESTIONS']:
                question = Question()
                question.question_text = item['question_text']
                question.explanation = item['explanation']
                question.options = json.dumps(item['options'])
                question.hint = item['hint']
                question.difficulty = item['difficulty_level']
                question.points = item['points']
                question.owner = owner[0]
                #question.target_exam = test.target_exam
                #question.subject = test.subject
                #question.topic = item.topic
                question.save()
                test.questions.add(question)
            data = {"status" : "success"}
            return JsonResponse(data)
        except Exception, e:
            raise e
开发者ID:adideshp,项目名称:Tutor,代码行数:34,代码来源:views.py


示例12: test_was_published_recently_with_recent_question

    def test_was_published_recently_with_recent_question(self):
	"""
	was_published_recently() should return True for questions whos pub_date is within the last day.
	"""
	time = timezone.now() + datetime.timedelta(hours=-1)
	recent_question=Question(pub_date=time)
	self.assertEqual(recent_question.was_published_recently(), True)
开发者ID:ghacer,项目名称:polls,代码行数:7,代码来源:tests.py


示例13: test_was_published_recently_wit_old_question

    def test_was_published_recently_wit_old_question(self):
	"""
	was_published_recently() should return False for question whose pub_date is in within the last day
	"""
	time = timezone.now() + datetime.timedelta(days=-30)
	old_question = Question(pub_date=time)
	self.assertEqual(old_question.was_published_recently(), False)
开发者ID:ghacer,项目名称:polls,代码行数:7,代码来源:tests.py


示例14: save

	def save(self, commit=True):
#		question = super(AskForm, self).save(commit=False)
		question = Question(title=self.cleaned_data['title'],
				    text=self.cleaned_data['text'],
				    author=self._user)
		question.save()
		return question
开发者ID:alysenko,项目名称:education-web-tech,代码行数:7,代码来源:forms.py


示例15: test_was_published_recently_with_future_question

 def test_was_published_recently_with_future_question(self):
     """
     was_published_recently() should return False for questions whose pub_date is in the future.
     """
     time = timezone.now() + datetime.timedelta(days=30)
     future_question = Question(pub_date=time)
     self.assertEqual(future_question.was_published_recently(), False)
开发者ID:nbkincaid,项目名称:django_project_tutorial,代码行数:7,代码来源:tests.py


示例16: askquestion

def askquestion(request):
    """提问模板"""
    name = request.session.get("name")
    if request.method == "POST":
        form = QuestionForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            title = data["title"]
            text = data["text"]
            qtype = data["q_type"]
            user = User.objects.get(name=name.split()[0])
            questiontype = QuestionType(name=qtype)
            questiontype.save()
            question = Question(user=user, title=title, text=text, q_type=questiontype)
            question.save()
            # return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
            return JsonResponse({"status": "ok"})
        else:
            # return HttpResponse(request.POST.get('title'))
            return render(request, "askquestion.html")
    if name:
        access_key = "wmN715-Lo5SC1jYIkuqObCLl1bhZoURTxewUGyq2"
        secret_key = "IXXeA4-Rzu9RB6nkf687UjQt9YCOp1JpWptm0C0y"
        bucket_name = "iforj"
        q = qiniu.Auth(access_key, secret_key)
        token = q.upload_token(bucket_name)
        return render(
            request, "askquestion.html", {"QuestionForm": QuestionForm, "uptoken": token, "name": name.split()}
        )
    else:
        return HttpResponseRedirect("/")
开发者ID:chengkeai,项目名称:iforj,代码行数:31,代码来源:views.py


示例17: QuestionTests

class QuestionTests(base.ExtendedTestCase):
    def setUp(self):
        super(QuestionTests, self).setUp()
        self.boragle = Boragle(name='test1', slugs = ['t1'], desc = 'desc', creator = self.creator)
        self.boragle.put()
        self.avatar = Avatar(boragle = self.boragle, creator = self.creator)
        self.avatar.put()
        self.question = Question(boragle = self.boragle, text = "why ?", creator = self.avatar)
        self.question.put()
        
    def test_creation(self):
        self.app.post('/t1/ask', dict(text = 'why? why? why?', details = 'simply, maybe'))
        question = Question.find_by_slug('why-why-why')
        self.assertTrue(question)
        self.assertEqual("why? why? why?",question.text)
        self.assertEqual("simply, maybe",question.details)
        self.assertEqual(self.creator.name,question.creator.creator.name)
    

    def test_creation_security(self):
        self.logout()
        self.app.post('/t1/ask', dict(text = 'why? why? why?', details = 'simply, maybe'), 
                status = 403)
        
    def test_answering_question(self):
        self.app.post(self.question.url, dict(answer = 'zimbly'))
        question = Question.get(self.question.key())
        self.assertEqual('zimbly', question.answers[0].text)
        self.assertEqual(self.creator.name, question.answers[0].creator.name)
        self.assertEqual(1, question.answer_count)
        
    def test_answering_question_security(self):
        self.logout()
        self.app.post(self.question.url, dict(answer = 'zimbly'), status = 403)
    
    def test_smoke_question_page(self):
        self.app.get(self.question.url)
    
    def test_voting_security(self):
        answer = Answer.create(question = self.question, text= 'fake answer', creator = self.avatar)
        self.app.get(answer.voting_url+'/up', status = 302)
        answer = Answer.get(answer.key())
        self.assertEqual(answer.vote_count, 1)
        self.logout()
        self.app.get(answer.voting_url+'/down', status = 302)
        answer = Answer.get(answer.key())
        self.assertEqual(answer.vote_count, 1)        
        
    
    def test_voting_up(self):
        answer = Answer.create(question = self.question, text= 'fake answer', creator = self.avatar)
        self.app.get(answer.voting_url+'/up', status = 302)
        answer = Answer.get(answer.key())
        self.assertEqual(answer.vote_count,1)
        self.app.get(answer.voting_url+'/down', status = 302)
        answer = Answer.get(answer.key())
        self.assertEqual(answer.vote_count,-1)
        
        
        
开发者ID:sudhirj,项目名称:boragle,代码行数:57,代码来源:web_question_tests.py


示例18: test_get_user

def test_get_user():
    user = User()
    user.username = u"test"
    user.set_password("test123")

    assert user.save()
    assert user._id

    q = Question()
    q.question = u"test"
    q.author = u"anon"
    q.user = user.username

    assert q.save(validate=True)
    assert q._id

    user_from_question = q.get_user()

    assert user_from_question._id == user._id

    q.user = u"anon!"

    q.save()

    assert not q.get_user()
开发者ID:fernandotakai,项目名称:questions,代码行数:25,代码来源:question_tests.py


示例19: question_result

def question_result(qid=None):
    import urllib
    escaped_url=urllib.quote_plus("http://www.isitfutureproof.com/question/" + qid)
    if ('vote_value' in request.form):
        agree = "didn't tell us if you agree or disagree"
        question = Question.get(qid)
        if (question.total == None):
            question.total = 0
        if (question.vote_no == None):
            question.vote_no = 0
        if (question.vote_yes == None):
            question.vote_yes = 0
        question.total = question.total + 1
        if (request.form['vote_value'] == "yes"):
            question.vote_yes = question.vote_yes +1
            agree = "disagree"
        if (request.form['vote_value'] == "no"):
            question.vote_no = question.vote_no +1
            agree = "agree"
        question.save()
        question = Question.get(qid)
        percent = 0
        stylepercent = "style-0"
        if (question.total > 0):
            percent = float(Decimal(str(float(1.0*question.vote_no/question.total)*100)).quantize(TWOPLACES))
            stylepercent = "style-" + str(int(percent))
        return render_template('question_result.html', escaped_url=escaped_url, qid=qid, question=question.question, percent=percent, vote_no=question.vote_no, total=question.total, agreed=agree, stylepercent=stylepercent)
    else:
        question = Question.get(qid)
        return render_template('question_clean.html', qid=qid, escaped_url=escaped_url, question=question.question)
开发者ID:johl,项目名称:futureproof,代码行数:30,代码来源:views.py


示例20: save

    def save(self):
	if self._user.is_anonymous():
    	    self.cleaned_data['author_id'] = 1
	else:     
    	    self.cleaned_data['author'] = self._user
	question = Question(**self.cleaned_data)
	question.save()
	return question
开发者ID:igorlutsenko,项目名称:stepic_web_project_6,代码行数:8,代码来源:forms.py



注:本文中的models.Question类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.Record类代码示例发布时间:2022-05-27
下一篇:
Python models.QotdGame类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap