示例#1
0
文件: views.py 项目: Nilkree/ask
def make_question(request, email):
    try:
        user = get_user_model().objects.get(email=email)
    except get_user_model().DoesNotExist:
        context = {"error": "Такого пользователя не существует"}
        return render(request, "website/make_question.html", context)
    if request.method == "POST":
        question = Question(to_user=user, text=request.POST.get("question"))
        if request.user.is_authenticated():
            question.from_user = request.user
        question.save()
        return redirect("site:wall")
    else:
        questions = Question.objects.filter(to_user=user, answered=True)
        print(questions)
        context = {"to_user": user, "questions": questions}
        context.update(csrf(request))
        return render(request, "website/make_question.html", context)
示例#2
0
文件: views.py 项目: Nilkree/ask
def make_question(request, email):
    try:
        user = get_user_model().objects.get(email=email)
    except get_user_model().DoesNotExist:
        context = {'error': 'Такого пользователя не существует'}
        return render(request, 'website/make_question.html', context)
    if request.method == 'POST':
        question = Question(to_user=user, text=request.POST.get('question'))
        if request.user.is_authenticated():
            question.from_user = request.user
        question.save()
        return redirect('site:wall')
    else:
        questions = Question.objects.filter(to_user=user, answered=True)
        print(questions)
        context = {'to_user': user, 'questions': questions}
        context.update(csrf(request))
        return render(request, 'website/make_question.html', context)
示例#3
0
def new_question(request):
    context = {}
    if request.method == 'POST':
        form = NewQuestionForm(request.POST)
        if form.is_valid():
           
            cleaned_data = form.cleaned_data
            question = Question()
            question.user = request.user
            question.category = cleaned_data['category']
            question.title = cleaned_data['title']
            question.body = cleaned_data['body'].encode('unicode_escape')
            question.views= 1 
            question.save()
           
            #Sending email when a new question is asked
            subject = 'New Forum Question'
            message = """
                The following new question has been posted in the FOSSEE Forum: <br>
                Title: <b>{0}</b><br>
                Category: <b>{1}</b><br>
                
                Link: <a href="{2}">{2}</a><br>
            """.format(
                question.title,
                question.category, 
                #question.tutorial, 
                'http://forums.fossee.in/question/'+str(question.id)
            )
            email = EmailMultiAlternatives(
                subject,'', 'forums', 
                ['*****@*****.**'],
                headers={"Content-type":"text/html;charset=iso-8859-1"}
            )
           
            email.attach_alternative(message, "text/html")
            email.send(fail_silently=True)
            
            return HttpResponseRedirect('/')
    else:
       
        category = request.GET.get('category')
        form = NewQuestionForm(category=category)
        context['category'] = category
    
    context['form'] = form
   
    context.update(csrf(request))
    return render(request, 'website/templates/new-question.html', context)
示例#4
0
def question_new():
    form = QuestionForm()
    if form.validate_on_submit():
        question = form.question.data

        author = current_user._get_current_object()
        q = Question(question=question, author=author)
        db.session.add(q)
        db.session.commit()
        flash("Done creating new question...")
        return redirect(url_for('main.question_detail', question_id=q.id))

    return render_template('/main/question.html', form=form)
示例#5
0
def new_question(request):
    context = {}
    if request.method == 'POST':
        form = NewQuestionForm(request.POST)
        if form.is_valid():
            cleaned_data = form.cleaned_data
            question = Question()
            question.uid = request.user.id
            question.category = cleaned_data['category'].replace(' ', '-')
            question.tutorial = cleaned_data['tutorial'].replace(' ', '-')
            question.minute_range = cleaned_data['minute_range']
            question.second_range = cleaned_data['second_range']
            question.title = cleaned_data['title']
            question.body = cleaned_data['body'].encode('unicode_escape')
            question.views = 1
            question.save()

            # Sending email when a new question is asked
            subject = 'New Forum Question'
            message = """
                The following new question has been posted in the Spoken Tutorial Forum: <br>
                Title: <b>{0}</b><br>
                Category: <b>{1}</b><br>
                Tutorial: <b>{2}</b><br>
                Link: <a href="{3}">{3}</a><br>
                Question: <b>{4}</b><br>
            """.format(
                question.title,
                question.category,
                question.tutorial,
                'http://forums.spoken-tutorial.org/question/' + str(question.id),
                question.body
            )
            email = EmailMultiAlternatives(
                subject, '', 'forums',
                ['*****@*****.**', '*****@*****.**'],
                headers={"Content-type": "text/html;charset=iso-8859-1"}
            )
            email.attach_alternative(message, "text/html")
            email.send(fail_silently=True)
            # End of email send

            return HttpResponseRedirect('/')
    else:
        # get values from URL.
        category = request.GET.get('category', None)
        tutorial = request.GET.get('tutorial', None)
        minute_range = request.GET.get('minute_range', None)
        second_range = request.GET.get('second_range', None)
        # pass minute_range and second_range value to NewQuestionForm to populate on select
        form = NewQuestionForm(category=category, tutorial=tutorial,
                               minute_range=minute_range, second_range=second_range)
        context['category'] = category

    context['form'] = form
    context.update(csrf(request))
    return render(request, 'website/templates/new-question.html', context)
def custom_field(request):
    data = {}
    requestProcessor = HttpRequestProcessor(request)  
    dajax = Dajax()
    
    ajax = requestProcessor.getParameter('ajax')
    if (ajax != None):
        if (ajax == 'create_custom_field'):
            data['form_id'] = 'create_custom_field'      

            data['field_title'] = requestProcessor.getParameter('field_title') 
            data['field_value'] = requestProcessor.getParameter('field_value') 
            data['jurisdiction_id'] = requestProcessor.getParameter('jurisdiction_id') 
            data['category_id'] = requestProcessor.getParameter('category_id')   
            data['current_category'] = requestProcessor.getParameter('current_category')      
            data['current_questions'] = requestProcessor.getParameter('current_questions')                                            
            
            if data['field_title'] == None:
                data['field_title'] = ''   
            if data['field_value'] == None:
                data['field_value'] = ''                      
                
            data['jurisdiction'] = Jurisdiction.objects.get(id=data['jurisdiction_id'])

            body = requestProcessor.decode_jinga_template(request,'website/blocks/create_custom_field.html', data, '') 
            dajax.assign('#fancyboxformDiv','innerHTML', body)
            script = requestProcessor.decode_jinga_template(request, 'website/blocks/create_custom_field.js', data, '')
            dajax.script(script)        
            dajax.script('controller.showModalDialog("#fancyboxformDiv");')

            return HttpResponse(dajax.json())  
        
        if (ajax == 'create_custom_field_submit'):  
            data = {}       
            data['form_id'] = 'create_custom_field'     
            data['field_title'] = requestProcessor.getParameter('field_title') 
            data['field_value'] = requestProcessor.getParameter('field_value') 
            data['jurisdiction_id'] = requestProcessor.getParameter('jurisdiction_id') 
            data['category_id'] = requestProcessor.getParameter('category_id')     
            current_category = requestProcessor.getParameter('current_category')   
            current_questions = requestProcessor.getParameter('current_questions') 
                                                               
            error_message = {}        
            error_message = validate_create_custom_field_form_data(data, data['form_id'])

            if len(error_message) == 0:
                msg_key = data['form_id']+ '_fail_reason'               
                try:
                    jurisdiction = Jurisdiction.objects.get(id=data['jurisdiction_id'])
                    
                    # look up template CF for this jurisdiction
                    templates = Template.objects.filter(jurisdiction=jurisdiction, template_type__iexact='CF')
                    if len(templates) > 0:
                        template = templates[0]
                    else:
                        template = Template()
                        template.template_type = 'CF'
                        template.name = 'Jurisdiction Custom Field Template'
                        template.jurisdiction_id = data['jurisdiction_id']
                        #template.create_datetime = datetime.datetime.now()
                        template.save()
                    # create the question

                    category_obj = QuestionCategory.objects.get(id=data['category_id'])
                    '''
                    questions = Question.objects.filter(category=category_obj, accepted=1).order_by('-display_order')
                    last_question = questions[0]
                    if last_question.display_order == None or last_question.display_order == '':
                        display_order = 0
                    else:
                        display_order = last_question.display_order
                    '''    
                    highest_display_order_obj = Question.objects.filter(category=category_obj, accepted=1).aggregate(Max('display_order'))
                    #print highest_display_order_obj
                    if highest_display_order_obj == None:
                        highest_display_order = 0
                    else:
                        highest_display_order = highest_display_order_obj['display_order__max']
                        
                    question_obj = Question();
                    question_obj.category_id = data['category_id']
                    question_obj.question = data['field_title']
                    question_obj.label = data['field_title']
                    question_obj.form_type = 'CF'
                    question_obj.qtemplate_id = template.id
                    question_obj.accepted = 1
                    question_obj.display_order = int(highest_display_order) + 5
                    #question_obj.create_datetime = datetime.datetime.now()
                    question_obj.creator_id = request.user.id
                    question_obj.save()
                    
                    template_question = TemplateQuestion()
                    template_question.template_id = template.id
                    template_question.question_id = question_obj.id
                    #template_question.create_datetime = datetime.datetime.now()
                    template_question.save()
                    # save the answer
                    data_answer = {}
                    data_answer['value'] = data['field_value']
                    answer = json.dumps(data_answer)   # to convert to json                    
                    is_callout=0           
                    answer_reference_class_obj = AnswerReference()
                    
                    #action_category_objs = ActionCategory.objects.filter(name__iexact='AddRequirement')
                    #action_category_obj = action_category_objs[0]   
                    validation_util_obj = FieldValidationCycleUtil()                    
                    arcf = validation_util_obj.save_answer(question_obj, answer, jurisdiction, 'AddRequirement', request.user, is_callout)
                    
                except Exception, e:
                    data[msg_key] = e.message
                    print e.message
        
            #else:
            if len(error_message) > 0:
                for msg_key in error_message.keys():
                    data[msg_key] = error_message.get(msg_key)  
                    
                    body = requestProcessor.decode_jinga_template(request,'website/blocks/create_custom_fields.html', data, '')     
                    dajax.assign('#fancyboxformDiv','innerHTML', body)
                    script = requestProcessor.decode_jinga_template(request, 'website/blocks/create_custom_fields.js', data, '')
                    dajax.script(script)
            else:
                data_cf = {}
                jurisdiction = Jurisdiction.objects.get(id=data['jurisdiction_id'])
                data_cf['jurisdiction'] = jurisdiction
                '''
                question_category_obj = QuestionCategory.objects.get(id=data['category_id'])  
                data['question_categories'] = QuestionCategory.objects.filter(id=data['category_id'])
                
                question_class_obj = Question()
                custom_questions = question_class_obj.get_custom_fields_by_jurisdiction_by_category(jurisdiction, data['category_id'])
                print custom_questions
                validation_util_obj = FieldValidationCycleUtil()
                data['action'] = 'refresh_ahj_qa'               

                if custom_questions != None and len(custom_questions) > 0:
                    for question in custom_questions:
                        data['question_content'][question_category_obj.id][question.id] = validation_util_obj.get_AHJ_question_data(request, jurisdiction, question, data)                
                '''
                
                '''
                validation_util_obj = FieldValidationCycleUtil()                        
                data_cf['this_question'] = question_obj               
                question_content = validation_util_obj.get_AHJ_question_data(request, jurisdiction, question_obj, data_cf)            
                for key in question_content.keys():
                    data_cf[key] = question_content.get(key)               
                                        
                body = requestProcessor.decode_jinga_template(request,'website/jurisdictions/AHJ_question_content_authenticated.html', data_cf, '')

                dajax.assign('#div_custom_question_content_'+str(category_obj.id),'innerHTML', body)
                script = requestProcessor.decode_jinga_template(request,'website/jurisdictions/AHJ_question_content.js', data, '')
                dajax.script(script)                        
                '''
                template_obj = Template()
                jurisdiction_templates = template_obj.get_jurisdiction_question_templates(jurisdiction)
               
                    
                data_cf['action'] = '/jurisdiction_id/'+str(jurisdiction.id)+'/'+current_category+'/'
                current_questions = current_questions.split(',')
                data_cf['custom_questions'] = Question.objects.filter(category=category_obj, accepted=1, qtemplate__in=jurisdiction_templates).exclude(id__in=(current_questions))
                body = requestProcessor.decode_jinga_template(request,'website/jurisdictions/AHJ_question_content_ajax_call.html', data_cf, '')                        
                dajax.assign('#div_custom_question_content_'+str(category_obj.id),'innerHTML', body)
                script = requestProcessor.decode_jinga_template(request, 'website/jurisdictions/AHJ_question_content_ajax_call.js', data_cf, '')
                dajax.script(script)                                             
                        ######################################################               
                      
                #data['custom_questions'] = custom_questions
                #data['custom_questions'] = {}
                #data['custom_questions'][question_category_obj.id] = custom_questions
                
                #body = requestProcessor.decode_jinga_template(request,'website/blocks/custom_fields.html', data, '')                                   
                #dajax.assign('#custom_fields_'+str(question_category_obj.id),'innerHTML', body)
                dajax.script('jQuery.fancybox.close();')  
                dajax.script("controller.showMessage('Custom field created.', 'success')") 
                dajax.script('controller.updateUrlAnchor("#create_custom_field");')
                
                if current_category == 'all_info':
                    question_categories = QuestionCategory.objects.filter(accepted=1)
                    data['category'] = 'All categories'
                else:
                    question_categories = QuestionCategory.objects.filter(name__iexact=category_obj.name)
                    data['category'] = category_obj.name

                #data['category'] = question_obj.category.name
                data['jurisdiction'] = jurisdiction
                validation_util_obj = FieldValidationCycleUtil()   
                data['top_contributors'] = validation_util_obj.get_top_contributors(jurisdiction, question_categories)  
                body = requestProcessor.decode_jinga_template(request,'website/blocks/top_contributors.html', data, '')   
                dajax.assign('#top_contributors','innerHTML', body)                
                
            return HttpResponse(dajax.json())  
def new_question(request):
    context = {}
    if request.method == 'POST':
        form = NewQuestionForm(request.POST)
        if form.is_valid():
            cleaned_data = form.cleaned_data
            question = Question()
            question.uid = request.user.id
            question.category = cleaned_data['category'].replace(' ', '-')
            question.tutorial = cleaned_data['tutorial'].replace(' ', '-')
            question.minute_range = cleaned_data['minute_range']
            question.second_range = cleaned_data['second_range']
            question.title = cleaned_data['title']
            question.body = cleaned_data['body'].encode('unicode_escape')
            question.views= 1 
            question.save()
            
            # Sending email when a new question is asked
            subject = 'New Forum Question'
            message = """
                The following new question has been posted in the Spoken Tutorial Forum: <br>
                Title: <b>{0}</b><br>
                Category: <b>{1}</b><br>
                Tutorial: <b>{2}</b><br>
                Link: <a href="{3}">{3}</a><br>
                Question: <b>{4}</b><br>
            """.format(
                question.title,
                question.category, 
                question.tutorial, 
                'http://forums.spoken-tutorial.org/question/'+str(question.id),
                question.body
            )
            email = EmailMultiAlternatives(
                subject,'', 'forums', 
                ['*****@*****.**', '*****@*****.**'],
                headers={"Content-type":"text/html;charset=iso-8859-1"}
            )
            email.attach_alternative(message, "text/html")
            email.send(fail_silently=True)
            # End of email send
            
            return HttpResponseRedirect('/')
    else:
        # get values from URL.
				category = request.GET.get('category', None)
				tutorial = request.GET.get('tutorial', None)
				minute_range = request.GET.get('minute_range', None)
				second_range = request.GET.get('second_range', None)
				# pass minute_range and second_range value to NewQuestionForm to populate on select
				form = NewQuestionForm(category=category, tutorial=tutorial, minute_range=minute_range,second_range=second_range)
				context['category'] = category
			
    context['form'] = form
    context.update(csrf(request))
    return render(request, 'website/templates/new-question.html', context)
示例#8
0
def custom_field(request):
    data = {}
    requestProcessor = HttpRequestProcessor(request)  
    dajax = Dajax()
    
    ajax = requestProcessor.getParameter('ajax')
    if (ajax != None):
        if (ajax == 'create_custom_field'):
            data['form_id'] = 'create_custom_field'      

            data['field_title'] = requestProcessor.getParameter('field_title') 
            data['field_value'] = requestProcessor.getParameter('field_value') 
            data['jurisdiction_id'] = requestProcessor.getParameter('jurisdiction_id') 
            data['category_id'] = requestProcessor.getParameter('category_id')   
            data['current_category'] = requestProcessor.getParameter('current_category')      
            
            if data['field_title'] == None:
                data['field_title'] = ''   
            if data['field_value'] == None:
                data['field_value'] = ''                      
                
            data['jurisdiction'] = Jurisdiction.objects.get(id=data['jurisdiction_id'])

            body = requestProcessor.decode_jinga_template(request,'website/blocks/create_custom_field.html', data, '') 
            dajax.assign('#fancyboxformDiv','innerHTML', body)
            script = requestProcessor.decode_jinga_template(request, 'website/blocks/create_custom_field.js', data, '')
            dajax.script(script)        
            dajax.script('controller.showModalDialog("#fancyboxformDiv");')

            return HttpResponse(dajax.json())  
        
        if (ajax == 'create_custom_field_submit'):  
            data = {}       
            data['form_id'] = 'create_custom_field'     
            data['field_title'] = requestProcessor.getParameter('field_title') 
            data['field_value'] = requestProcessor.getParameter('field_value') 
            data['jurisdiction_id'] = requestProcessor.getParameter('jurisdiction_id') 
            data['category_id'] = requestProcessor.getParameter('category_id')     
            current_category = requestProcessor.getParameter('current_category')   
            current_questions = requestProcessor.getParameter('current_questions') 
                                                               
            error_message = {}        
            error_message = validate_create_custom_field_form_data(data, data['form_id'])

            if len(error_message) == 0:
                msg_key = data['form_id']+ '_fail_reason'               
                try:
                    jurisdiction = Jurisdiction.objects.get(id=data['jurisdiction_id'])
                    
                    # look up template CF for this jurisdiction
                    templates = Template.objects.filter(jurisdiction=jurisdiction, template_type__iexact='CF', accepted = 1)
                    if len(templates) > 0:
                        template = templates[0]
                    else:
                        template = Template()
                        template.template_type = 'CF'
                        template.name = 'Jurisdiction Custom Field Template'
                        template.jurisdiction_id = data['jurisdiction_id']
                        #template.create_datetime = datetime.datetime.now()
                        template.accepted = 1
                        template.save()
                    # create the question

                    category_obj = QuestionCategory.objects.get(id=data['category_id'])
                    '''
                    questions = Question.objects.filter(category=category_obj, accepted=1).order_by('-display_order')
                    last_question = questions[0]
                    if last_question.display_order == None or last_question.display_order == '':
                        display_order = 0
                    else:
                        display_order = last_question.display_order
                    '''    
                    highest_display_order_obj = Question.objects.filter(category=category_obj, accepted=1).aggregate(Max('display_order'))
                    if highest_display_order_obj == None:
                        highest_display_order = 0
                    else:
                        highest_display_order = highest_display_order_obj['display_order__max']
                        
                    question_obj = Question();
                    question_obj.category_id = data['category_id']
                    question_obj.question = data['field_title']
                    question_obj.label = data['field_title']
                    question_obj.form_type = 'CF'
                    question_obj.qtemplate_id = template.id
                    question_obj.accepted = 1
                    question_obj.display_order = int(highest_display_order) + 5
                    #question_obj.create_datetime = datetime.datetime.now()
                    question_obj.creator_id = request.user.id
                    question_obj.save()
                    
                    template_question = TemplateQuestion()
                    template_question.template_id = template.id
                    template_question.question_id = question_obj.id
                    #template_question.create_datetime = datetime.datetime.now()
                    template_question.save()
                    # save the answer
                    data_answer = {}
                    data_answer['value'] = data['field_value']
                    answer = json.dumps(data_answer)   # to convert to json                    
                    is_callout=0           
                    answer_reference_class_obj = AnswerReference()
                    
                    #action_category_objs = ActionCategory.objects.filter(name__iexact='AddRequirement')
                    #action_category_obj = action_category_objs[0]   
                    validation_util_obj = FieldValidationCycleUtil()                    
                    arcf = validation_util_obj.save_answer(question_obj, answer, jurisdiction, 'AddRequirement', request.user, is_callout)
                    
                except Exception, e:
                    data[msg_key] = e.message
        
            #else:
            if len(error_message) > 0:
                for msg_key in error_message.keys():
                    data[msg_key] = error_message.get(msg_key)  
                    
                    body = requestProcessor.decode_jinga_template(request,'website/blocks/create_custom_field.html', data, '')
                    dajax.assign('#fancyboxformDiv','innerHTML', body)
                    script = requestProcessor.decode_jinga_template(request, 'website/blocks/create_custom_field.js', data, '')
                    dajax.script(script)
            else:
                data_cf = {}
                jurisdiction = Jurisdiction.objects.get(id=data['jurisdiction_id'])
                data_cf['jurisdiction'] = jurisdiction
                template_obj = Template()
                jurisdiction_templates = template_obj.get_jurisdiction_question_templates(jurisdiction)
               
                    
                data_cf['action'] = '/jurisdiction_id/'+str(jurisdiction.id)+'/'+current_category+'/'
                  
                data_cf = get_question_data(request, jurisdiction, question_obj, data)
                body = requestProcessor.decode_jinga_template(request,'website/jurisdictions/AHJ_cqa_qa.html', data_cf, '')
                script = requestProcessor.decode_jinga_template(request,'website/jurisdictions/AHJ_cqa_qa.js' , data, '')
                dajax.script(script)                                                   
            
                dajax.assign('#div_custom_question_content_'+str(data['category_id']),'innerHTML', body)    
                        
                        ######################################################               
                      
                #data['custom_questions'] = custom_questions
                #data['custom_questions'] = {}
                #data['custom_questions'][question_category_obj.id] = custom_questions
                
                #body = requestProcessor.decode_jinga_template(request,'website/blocks/custom_fields.html', data, '')                                   
                #dajax.assign('#custom_fields_'+str(question_category_obj.id),'innerHTML', body)
                dajax.script('jQuery.fancybox.close();')  
                dajax.script("controller.showMessage('Custom field created.', 'success')") 
                dajax.script('controller.updateUrlAnchor("#create_custom_field");')
                
                data = {}
                if current_category == 'all_info':
                    question_categories = QuestionCategory.objects.filter(accepted=1)
                    data['category'] = 'All categories'
                else:
                    question_categories = QuestionCategory.objects.filter(name__iexact=category_obj.name)
                    data['category'] = category_obj.name

                #data['category'] = question_obj.category.name
                data['jurisdiction'] = jurisdiction
                
                data['top_contributors'] = get_ahj_top_contributors(jurisdiction, current_category)  
                body = requestProcessor.decode_jinga_template(request,'website/jurisdictions/AHJ_top_contributors.html', data, '')   
                dajax.assign('#top-contributor','innerHTML', body)                           
                
            return HttpResponse(dajax.json())  
示例#9
0
    ['Czy skorzystałby/skorzystałaby Pan(i) z możliwości ingerencji w swój materiał genetyczny lub w materiał genetyczny swojego przyszłego dziecka w celu polepszenia swoich genów lub przekazania wybranych genów? Przy czym mając 100% pewności bezpieczeństwa takiego zabiegu.', ['Tak', 'Nie']],
    ['Czy byłby/byłaby Pan(i) zainteresowany/a codziennym i ciągłym przekazywaniem danych o własnym zdrowiu przez odpowiednie czujniki, aby skorzystać ze spersonalizowanego leczenia?', ['Tak', 'Nie']],
    ['Będąc osobą wymagającą opieki chciałby/chciałaby Pan(i), aby rolę opiekuna pełnił ...', ['Spersonalizowany robot dostępny całodobowo posiadający wszystkie konieczne funkcjonalności', 'Człowiek']],
    ['Czy chciałaby/chciałaby Pan(i) nosić inteligentną koszulkę, która całodobowo rejestruje stan zdrowia przesyłając dane do odpowiedniego urządzenia (np. smartfona)?', ['Tak', 'Nie']],
    ['Czy chciałby/chciałaby Pan(i) posiadać tatuaż, który całodobowo rejestruje stan zdrowia przesyłając dane do odpowiedniego urządzenia (np. smarfona)?', ['Tak', 'Nie']],
    ['Czy chciałaby/chciałaby Pan(i) posiadać wszczepiony chip, który całodobowo rejestruje stan zdrowia przesyłając dane do odpowiedniego urządzenia (np. smarfona)?', ['Tak', 'Nie']]
]

# WARNING! DELETING ENTIRE DATABASE
db.drop_all()

# CREATE DATABASE
db.create_all()

# CONSTANT DATA IN DATABASE 
q1 = Question(text=questions_options_experience[0][0])
q2 = Question(text=questions_options_experience[1][0])
q21 = Question(text=questions_options_experience[2][0])
q3 = Question(text=questions_options_fears[0][0])
q4 = Question(text=questions_options_fears[1][0])
q5 = Question(text=questions_options_fears[2][0])
q6 = Question(text=questions_options_knowledge[0][0])
q7 = Question(text=questions_options_knowledge[1][0])
q8 = Question(text=questions_options_knowledge[2][0])
q9 = Question(text=questions_options_knowledge[3][0])
q10 = Question(text=questions_options_knowledge[4][0])
q11 = Question(text=questions_options_expectations[0][0])
q12 = Question(text=questions_options_expectations[1][0])
q13 = Question(text=questions_options_expectations[2][0])
q14 = Question(text=questions_options_expectations[3][0])
q15 = Question(text=questions_options_expectations[4][0])
示例#10
0
def hand_form(request):
    if request.method == 'POST':
        age = request.POST.get('age')
        gender = request.POST.get('gender')
        edu = request.POST.get('edu')
        isGlasses = request.POST.get('isGlasses')
        pho = request.POST.get('pho')
        screen = request.POST.get('screen')

        code = generateCode(6)
        #code = 'NLIEGG'
        findUser = Users.objects.filter(check_list=code)
        while findUser:
            code = generateCode(6)
            findUser = Users.objects.filter(check_list=code)
        '''
        users = Users.objects.all().order_by("id")
        i = 1
        for user_num in users:
            if i != user_num.id:
                break
            i += 1
        '''
        user = Users(check_list=code, record_now=1)
        user.save()
        qa = Question(user_id=user.id,
                      age=age,
                      gender=gender,
                      edu=edu,
                      isGlasses=isGlasses,
                      pho=pho,
                      screen=screen[0:30])
        qa.save()
        #获得需要评价的总数和具体条目
        #img_index = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26,  29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 40, 41, 42, 43, 44, 45, 46, 47, 48, 51, 53, 54, 55, 56]
        #tiaomu1 = [(4, 14), (8, 9), (5, 12), (3, 13), (6, 10), (7, 11), (2, 12), (4, 13), (15, 16), (6, 11), (9, 10), (7, 13), (3, 15), (8, 14), (4, 10), (2, 7), (5, 15), (12, 16), (8, 13), (3, 9), (4, 16), (12, 15), (2, 9), (10, 14), (7, 16), (5, 9), (8, 15), (7, 14), (4, 9), (2, 16), (7, 12), (8, 11), (10, 13), (9, 16), (14, 15), (5, 6), (2, 11), (9, 15), (3, 12), (5, 10), (6, 9), (2, 3), (12, 13), (4, 6), (3, 7), (2, 5), (6, 15), (9, 11), (2, 10), (4, 5), (7, 15), (8, 10), (11, 14), (5, 7), (6, 12), (13, 14), (3, 8), (5, 11), (2, 13), (8, 12), (4, 11), (3, 10), (13, 15), (4, 8), (6, 14), (3, 16), (4, 15), (6, 13), (9, 12), (7, 10), (11, 13), (6, 8), (5, 16), (11, 12), (2, 15), (6, 7), (5, 13), (10, 11), (2, 4), (5, 14), (3, 6), (2, 8), (11, 16), (4, 7), (3, 14), (11, 15), (4, 12), (3, 5), (7, 8), (10, 12), (3, 11), (8, 16), (2, 14), (3, 4), (7, 9), (2, 6), (13, 16), (5, 8), (9, 14), (6, 16), (10, 15), (12, 14), (9, 13), (14, 16), (10, 16)]
        #tiaomu_list = [Tiaomu(img1 = i[0], img2 = i[1]) for i in tiaomu1]
        #Tiaomu.objects.bulk_create(tiaomu_list)

        #group = [(0,15), (15,30), (30, 45),(45,60), (60, 75), (75, 90), (90, 105)]
        #nightImg = [107,108,109,110,111,112,113,116,117,119,122,124,125,126,127,128,129,130,131,132,133,134,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,153,154,155,156,158,160,161]
        #random.shuffle(nightImg)

        lab = Lab.objects.get(status=1)
        record_all = lab.num
        user.record_all = record_all
        user.save()
        device = lab.devices.split(',')
        co_list = lab.collections.split(',')
        photo_list_all = []
        root_device = os.path.join(STATIC_ROOT, "D{}".format(device[0]))

        for co in co_list:

            root_co = os.path.join(root_device, 'co{}'.format(co))

            photo_list = os.listdir(root_co)
            if 'xml' in photo_list:
                photo_list.remove('xml')
            photo_list.sort(key=lambda x: int(x))
            photo_list_all.append(photo_list)

        if lab.func == 1:
            for i in range(record_all):
                aa = random.choice(photo_list_all)
                img = random.choice(aa)
                D1 = int(random.choice(device))
                D2 = int(random.choice(device))
                while D1 == D2:
                    D2 = int(random.choice(device))
                record = Records(user_id=user.id,
                                 user_record_id=i + 1,
                                 device1=D1,
                                 device2=D2,
                                 co1=int(co_list[photo_list_all.index(aa)]),
                                 co2=int(co_list[photo_list_all.index(aa)]),
                                 img_num1=int(img),
                                 img_num2=int(img))
                record.save()
        else:
            for i in range(record_all):
                device_rand = random.choice(device)
                aa = random.choice(photo_list_all)
                img1 = random.choice(aa)
                img2 = random.choice(aa)
                while img1 == img2:
                    img2 = random.choice(aa)
                record = Records(user_id=user.id,
                                 user_record_id=i + 1,
                                 device1=device_rand,
                                 device2=device_rand,
                                 co1=int(co_list[photo_list_all.index(aa)]),
                                 co2=int(co_list[photo_list_all.index(aa)]),
                                 img_num1=img1,
                                 img_num2=img2)
                record.save()
        '''
        lab_co2 = [i for i in range(11,61)]
        lab_co4 = [i for i in range(5,55)]
        #group_id = user.id % len(group)
        group_id = user.id % 2
        if group_id==0:
            lab_now = lab_co2
            co_now = 2
        else:
            lab_now = lab_co4
            co_now = 4
        
        #tiaomuGet = Tiaomu.objects.all()[group[group_id][0]:group[group_id][1]]

        record_all = 60
        user.record_all = record_all
        user.save()

        for i in range(1,61):
            D1 = random.randint(1,10)
            D2 = random.randint(1,10)
            while D1 ==D2:
                D2 = random.randint(1,10)
            record = Records(user_id=user.id,user_record_id = i, device1=10, device2=10, co1 = 7, co2 = 7, img_num1=D1,img_num2=D2)
            record.save()
        '''
        '''
        record_list = []
        for i in range(1,51):
            D1 = random.randint(1,7)
            D2 = random.randint(1,7)
            while D1 ==D2:
                D2 = random.randint(1,7)
            record_list.append([D1,D2,co_now,lab_now[i-1],lab_now[i-1]])
        for i in range(1,7):
            D1 = random.randint(1,7)
            D2 = random.randint(1,7)
            while D1 ==D2:
                D2 = random.randint(1,7)
            record_list.append([10, 10, i, D1, D2])
        random.shuffle(record_list)
        for i in range(1,5):
            j = 5-i
            record_now_repeat = record_list[(j-1)*14]
            if record_now_repeat[0]==record_now_repeat[1]:
                record_list.insert(j*14, [10, 10, record_now_repeat[2], record_now_repeat[4], record_now_repeat[3]])
            else:
                record_list.insert(j*14, [record_now_repeat[1], record_now_repeat[0], record_now_repeat[2], record_now_repeat[3], record_now_repeat[4]])
        i = 1
        for record_item in record_list:
            record = Records(user_id=user.id,user_record_id = i, device1=record_item[0], device2=record_item[1], co1 = record_item[2], co2 = record_item[2], img_num1=record_item[3],img_num2=record_item[4])
            record.save()
            i+=1
        '''
        #i = 46
        # for couple in tiaomuGet:
        #     record = Records(user_id=user.id,user_record_id = i, device1=6, device2=6, co1 = 1, co2 = 1,img_num1=couple.img1,img_num2=couple.img2)
        #     record.save()
        #     if i == record_all:break
        #     i = i+1

        response = JsonResponse({'state': 'ok', 'code': code})
        response.set_cookie("user_check_code", code, 60 * 60 * 24 * 7)

        return response
    else:
        return JsonResponse({'state': 'fail'})
示例#11
0
def show_faqs(request):
    return render_to_response('faq.html',
            {'faq':Question.getFaqs(request.LANGUAGE_CODE)},
        context_instance=RequestContext(request))