当前位置: 首页>>代码示例>>Python>>正文


Python Survey.save方法代码示例

本文整理汇总了Python中survey.models.Survey.save方法的典型用法代码示例。如果您正苦于以下问题:Python Survey.save方法的具体用法?Python Survey.save怎么用?Python Survey.save使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在survey.models.Survey的用法示例。


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

示例1: post

# 需要导入模块: from survey.models import Survey [as 别名]
# 或者: from survey.models.Survey import save [as 别名]
 def post(self, request, *args, **kwargs):
     warnings = []
     data = json.loads(request.POST.get('r'))
     title = data.get('title', '')
     slug = slugify(data.get('slug') or title)
     if not slug:
         warnings.append(_('Please enter a valid title.'))
         return HttpResponse(json.dumps({'status': 'failure', 'warnings': warnings}), mimetype='application/json')
     try:
         survey = self.get_object()
         if slug != survey.slug:
             warnings.append(_("This survey's URL has been changed. Be sure to update any QR code images."))
     except AttributeError:
         survey = Survey(creator=request.user)
     survey.title = title
     survey.slug = slug
     survey.description = data.get('description', '')
     try:
         survey.save()
     except IntegrityError:
         warnings = [_('That title is already taken. Please choose a different one.')]
         return HttpResponse(json.dumps({'status': 'failure', 'warnings': warnings}), mimetype='application/json')
     # delete existing questions
     # due to cascading deletes, this will also delete choices
     QuestionGroup.objects.filter(pk__in=survey.question_set.all().values_list('group')).delete()
     survey.question_set.all().delete()
     questions = data.get('questions', [])
     groups = data.get('groups', [])
     survey.add_questions(questions, groups)
     return HttpResponse(json.dumps({'status': 'success', 'warnings': warnings, 'url': reverse('surveydashboard', args=[survey.slug])}), mimetype='application/json')
开发者ID:ThatClyde,项目名称:django-resnet-survey,代码行数:32,代码来源:views.py

示例2: test_save_modified_time

# 需要导入模块: from survey.models import Survey [as 别名]
# 或者: from survey.models.Survey import save [as 别名]
 def test_save_modified_time(self):
     s = Survey(name='Survey')
     minute_slice = slice(0, 17)
     time = str(datetime.datetime.now())
     s.save()
     saved_time = str(s.created_at)
     self.assertEqual(saved_time[minute_slice], time[minute_slice])
开发者ID:bbuhai,项目名称:dlp-django-survey,代码行数:9,代码来源:test_models.py

示例3: submit

# 需要导入模块: from survey.models import Survey [as 别名]
# 或者: from survey.models.Survey import save [as 别名]
def submit(request):
    if request.method == 'POST':
        s = Survey(data = request.raw_post_data,
                   remote_addr = request.META["REMOTE_ADDR"],
                   user_agent = request.META["HTTP_USER_AGENT"])
        s.save()

    return HttpResponse("OK")
开发者ID:openmir,项目名称:openmir,代码行数:10,代码来源:views.py

示例4: handle

# 需要导入模块: from survey.models import Survey [as 别名]
# 或者: from survey.models.Survey import save [as 别名]
    def handle(self, *args, **options):
        # TODO: Remove or improve before production...
        logger.info('Deleting all surveys...')

        User.objects.filter(is_staff=False).delete()
        Survey.objects.all().delete()
        ChallengeDetail.objects.all().delete()

        logger.info('Starting import...')
        df = pd.read_excel(path.join(settings.BASE_DIR, 'respondents.xlsx'), sheetname='Delegates')
        df.fillna('', inplace=True)

        for idx, survey in df.iterrows():
            data_raw = survey.to_dict()
            data = {k: str(v).strip() for k, v in data_raw.items()}

            try:
                country = Country.objects.get(name=data.get('country_of_operation'))
                data.update({'country_of_operation': country})

            except Country.DoesNotExist:
                logger.warning('Could not find country %s' % data.get('country_of_operation'))
                data.update({'country_of_operation': None})

            del data['countries']

            # Create and associate user
            username = slugify(data.get('name')).replace('-', '_')
            slug = '{0}_{1}'.format(data.get('slug')[2:] or slug_generator(), username)
            logger.info(slug)
            user = User.objects.create_user(username[:30], data.get('email', ''), slug)

            survey = Survey(**data)
            survey.slug = slug
            survey.user = user
            survey.save()
            assign_perm('change_survey', user, obj=survey)

            # Creating challenges
            # for challenge in Challenge.objects.all():
            #     ChallengeDetail.objects.create(owner=slug, challenge=challenge)

            for rank in range(1, 4):
                ChallengeDetail.objects.create(respondent=survey, rank=rank)

            # try:
            #     Survey(**data).save()
            # except IntegrityError:
            #     logger.excep('Integ exisits: %s ' % data)
            # except:
            #     logger.exception(data)
            # else:
            #     for challenge in Challenge.objects.all():
            #         ChallengeDetail.objects.create(slug, challenge)

        logger.info('Done')
开发者ID:jr-minnaar,项目名称:djskel,代码行数:58,代码来源:import_delegates.py

示例5: login_user

# 需要导入模块: from survey.models import Survey [as 别名]
# 或者: from survey.models.Survey import save [as 别名]
def login_user(request, slug):
    logger.info('Slug is: {}, trying to log in...'.format(slug))

    request.session['survey_slug'] = slug
    request.session.save()
    survey_instance = None

    try:
        survey_instance = Survey.objects.get(slug=slug)

    except Survey.DoesNotExist:
        logger.info('Survey does not exist...')
        user = User(username=slug[30:])
        user.set_password(slug)
        user.email = ''
        user.save()
        logger.info('Saved new user... {}'.format(user))
        survey_instance = Survey(slug=slug, user=user)
        survey_instance.save()
        logger.info('Saved new survey... {}'.format(survey_instance))

        for rank in range(1, 4):
            ChallengeDetail.objects.create(respondent=survey_instance, rank=rank)
            logger.info('Added new ChallengeDetail with respondent = {} and rank = {}'.format(survey_instance, rank))

    else:
        logger.info('Found survey and use!:')

    finally:
        if request.user.is_staff:
            logger.info('Staff in the house!!')

        else:
            user = authenticate(username=survey_instance.user.username, password=slug)
            logger.info('Not staff, who is %s' % survey_instance.user.username)

            if user is not None:
                # If staff member is testing
                if user.is_active:
                    logger.info('User is active!')
                    login(request, user)
                    # Redirect to a success page
                else:
                    logger.warn('User not active')
                    pass
                    # Return a 'disabled account' error message
            else:
                logger.warn('Authentication Failed')
                pass
                # Return an 'invalid login' error message.

        # logger.info('Confirming that survey_slug is stored: {}'.format(request.session['survey_slug']))
        return HttpResponseRedirect(reverse('survey:about'))
开发者ID:jr-minnaar,项目名称:djskel,代码行数:55,代码来源:views.py

示例6: create_survey

# 需要导入模块: from survey.models import Survey [as 别名]
# 或者: from survey.models.Survey import save [as 别名]
def create_survey(request):
    if request.POST:
        survey_title = request.POST.get("survey_title")
        survey_description = request.POST.get("survey_description")
        if survey_title == "New Survey(Click to change)":
            survey_title = "No title"
        if survey_description == "Add description here" or survey_description == "Click here to add...":
            survey_description = ""
        publishBool = request.POST.get("publishBool")
        survey = Survey(title=survey_title)
        survey.description = survey_description
        creator = User.objects.get(id = int(request.POST.get( "creatorID")))
        survey.user = creator
        survey.theme_name = request.POST.get("theme_name")
        deadline = request.POST.get("survey_deadline")
        survey.deadline = datetime.strptime(deadline.strip(), "%d/%m/%Y")
        survey.save()
        collaborators = request.POST.get("collaborators")
        collaborators = collaborators.split(",")
        try:
            collaborators.remove("")
        except BaseException as e:
            pass
        for collaborator_id in collaborators:
            collaboration = Collaboration()
            collaboration.user = User.objects.get(id = int(collaborator_id))
            collaboration.survey = survey
            collaboration.is_active = True
            collaboration.save()

        if publishBool == 'true':
            survey.is_published = True
            survey.save()
        surveyID = survey.id
        dict = {"surveyID": surveyID, "survey_key": survey.key}
        return HttpResponse(simplejson.dumps(dict), mimetype='application/javascript')
    return error_jump(request)
开发者ID:Copperfield,项目名称:ntusurvey,代码行数:39,代码来源:views.py

示例7: SurveyModel

# 需要导入模块: from survey.models import Survey [as 别名]
# 或者: from survey.models.Survey import save [as 别名]
class SurveyModel(TestCase):
    """Test Survey, Section, Branching, Result, ResultAggregate Model"""

    fixtures = ['auth_user.json', 'gateway.json', 'dialer_setting.json',
                'user_profile.json',  # 'contenttype.json',
                'phonebook.json', 'contact.json',
                'dnc_list.json', 'dnc_contact.json',
                'campaign.json', 'subscriber.json',
                'callrequest.json', 'voipcall.json',
                'survey_template.json', 'survey.json',
                'section_template.json', 'section.json',
                'branching.json',
                ]

    def setUp(self):
        self.user = User.objects.get(username='admin')

        # Survey_template model
        self.survey_template = Survey_template(
            name='test_survey',
            user=self.user,
        )
        self.survey_template.save()

        # Survey model
        self.survey = Survey(
            name='test_survey',
            user=self.user,
        )
        self.survey.save()
        self.assertEqual(self.survey.__unicode__(), u'test_survey')

        # Section_template
        self.section_template = Section_template.objects.get(pk=1)
        self.section_template.survey.name = 'New Survey'
        self.section_template.save()

        # Section model
        self.section = Section.objects.get(pk=1)
        self.section.save()
        self.assertTrue(self.section.__unicode__())

        # Branching_template model
        self.branching_template = Branching_template(
            keys=5,
            section=self.section_template,
        )
        self.branching_template.save()

        # Branching model
        self.branching = Branching(
            keys=5,
            section=self.section,
        )
        self.branching.save()
        self.assertTrue(self.branching.__unicode__())

        # Result model
        self.result = Result(
            section=self.section,
            callrequest_id=1,
            response='apple'
        )
        self.result.save()
        self.assertEqual(
            self.result.__unicode__(), '[1] [1] call transfer = apple')

        # ResultAggregate model
        self.result_aggregate = ResultAggregate(
            survey=self.survey,
            section=self.section,
            count=1,
            response='apple'
        )
        self.result_aggregate.save()
        self.assertEqual(
            self.result_aggregate.__unicode__(), '[1] [1] call transfer = apple')

    def test_survey_forms(self):
        self.assertEqual(self.survey_template.name, "test_survey")
        #self.assertEqual(self.section_template.survey, self.survey_template)
        self.assertEqual(self.branching_template.section, self.section_template)
        self.assertEqual(self.result.section, self.section)

        form = PlayMessageSectionForm(self.user, instance=self.section_template)
        obj = form.save(commit=False)
        obj.question = "test question"
        obj.type = 1
        obj.survey = self.survey_template
        obj.save()

        form = MultipleChoiceSectionForm(self.user, instance=self.section_template)
        obj = form.save(commit=False)
        obj.type = 2
        obj.question = "test question"
        obj.key_0 = "apple"
        obj.survey = self.survey_template
        obj.save()

        form = RatingSectionForm(self.user,
#.........这里部分代码省略.........
开发者ID:aristide,项目名称:newfies-dialer,代码行数:103,代码来源:tests.py

示例8: buildSurvey

# 需要导入模块: from survey.models import Survey [as 别名]
# 或者: from survey.models.Survey import save [as 别名]
def buildSurvey(user,phone_number):
    print "build survey"
    thedatetime = datetime.datetime.now().strftime("%Y:%m:%d:%H:%M:%S")
    title = str(phone_number) + "/" + thedatetime
    survey = Survey(title = title)
    survey.save()
    textmessagelist = []
    for conver in user.sms_conversation_set.all():
        for message in conver.sms_message_set.all():
            if message.from_last_day():
                textmessagelist.append("  recipient: " + message.recipient)
                textmessagelist.append("\t message: " + decrypt(key,message.SmSbody))
    facemessagelist = []
    for faceConver in user.facebook_conversation_set.all():
        for faceMessage in faceConver.facebook_messages_set.all():
            if faceMessage.from_last_day():
                facemessagelist.append("  text: " + decrypt(key,faceMessage.body))
    faceactlist = []
    faceComm = []
    for faceact in user.facebook_activity_set.all():
        if faceact.from_last_day():
	    try:
            	md = decrypt(key, faceact.message)
	    except Exception as e:
		print e
	    fmsg = faceact.message
	    #print "new facebook key=[%s] orig=[%s] decrypt=[%s, %d]" % (key, faceact.message, md, len(md))
            if decrypt(key,faceact.message):
                faceactlist.append("  activity:" + decrypt(key,faceact.message))
		#print "added activity", len(faceactlist)
	    else:
		#print "no activity. decrypt failed?"
		pass
        for com in faceact.facebook_comments_set.all():
            if decrypt(key,com.text):
                faceComm.append(" comment:" + decrypt(key,com.text))
    twitterStatus = []
    qs = list(twitter_status.objects.filter(author = user))
    for twitterstatus in qs:
        if twitterstatus.from_last_day():
            twitterStatus.append("   twitter status :" + twitterstatus.body + "\n")
    print(textmessagelist)
    if not textmessagelist:
        textmessagelist.append("No text messages sent in last day")
    text = "Text messages from last day: \n" + "\n".join(textmessagelist)
    q1 = survey.question_set.create(text = text,atype=1)
    y1 = q1.choice_set.create(choice_text="Yes")
    n1 = q1.choice_set.create(choice_text="No")
    print(facemessagelist)
    if not facemessagelist:
        facemessagelist.append("No facebook instant massages from last day")
    text2 = "Facebook message from last day: \n" + "\n".join(facemessagelist)+ "\n".join(faceComm)
    q2 = survey.question_set.create(text = text2,atype=1)
    y2 = q2.choice_set.create(choice_text="Yes")
    n2 = q2.choice_set.create(choice_text="No")
    print("activity list %s %d", str(faceactlist), len(faceactlist))
    if not faceactlist:
        faceactlist.append("No facebook activities from last day")
    text4 = "Facebook activities from last day: \n" + "\n".join(faceactlist)
    q4 = survey.question_set.create(text = text4,atype=1)
    y4 = q4.choice_set.create(choice_text="Yes")
    n4 = q4.choice_set.create(choice_text="No")
    if not twitterStatus:
        twitterStatus.append("No new twitter status")
    text3 = "Twitter status from last day: \n" + "\n".join(twitterStatus)
    q3 = survey.question_set.create(text = text3,atype=1)
    y3 = q3.choice_set.create(choice_text="Yes")
    n3 = q3.choice_set.create(choice_text="No")
    return survey
开发者ID:ericwangtengyu,项目名称:DjangoServer_CyberBullying,代码行数:71,代码来源:views.py

示例9: save_survey

# 需要导入模块: from survey.models import Survey [as 别名]
# 或者: from survey.models.Survey import save [as 别名]
def save_survey(request, surveyID):
    if request.POST:
        question_type = request.POST.get("question_type")
        question_no = request.POST.get("question_no")
        question_helptext = request.POST.get("question_helptext")
        is_required = request.POST.get("is_required")
        if question_helptext == "Click here to add...":
            question_helptext == ""
        question_title = request.POST.get("question_title")
        selections = request.POST.get("selections")
        attributes = request.POST.get("attributes")
        if int(surveyID) == 0:
            survey = Survey(title="no title")
            survey.save()
            surveyID = survey.id
        if question_type == "paragraph":
            question = ParagraphQuestion()
        elif question_type == "numeric":
            question = NumericQuestion()
        elif question_type == "multiplechoice":
            question = MultipleChoiceQuestion()
        elif question_type == "checkbox":
            question = CheckboxQuestion()
        elif question_type == "scale":
            question = ScaleQuestion()
        elif question_type == "text":
            question = TextQuestion()
        elif question_type == "date":
            question = DateQuestion()
        else:
            return
        question.survey = Survey.objects.get(id=surveyID)
        question.id_in_survey = question_no
        question.title = question_title.strip()
        question.help_text = question_helptext
        question.max_no_characters = 0
        if is_required == 'true':
            question.is_required = True
        else:
            question.is_required = False
        question.save()
        if question_type == "paragraph":
            attributes_list = attributes.split("@#@")
            question.max_no_characters = int(attributes_list[0])
        elif question_type == "numeric":
            attributes_list = attributes.split("@#@")
            question.max_value = float(attributes_list[0])
            question.min_value = float(attributes_list[1])
        elif question_type == "multiplechoice":
            choices = selections.split("@#@")
            choices.pop()
            count = 0
            for choice_label in choices:
                count += 1
                choice = MultipleChoice()
                choice.question = question
                choice.label = choice_label
                choice.id_in_question = count
                choice.save()
        elif question_type == "checkbox":
            attributes_list = attributes.split("@#@")
            question.max_checked = int(attributes_list[0])
            question.min_checked = int(attributes_list[1])
            choices = selections.split("@#@")
            choices.pop()
            count = 0
            for choice_label in choices:
                count += 1
                choice = CheckboxChoice()
                choice.question = question
                choice.label = choice_label
                choice.id_in_question = count
                choice.save()
        elif question_type == "scale":
            attributes_list = attributes.split("@#@")
            question.max_value = float(attributes_list[0])
            question.min_value = float(attributes_list[1])
            question.increment = float(attributes_list[2])
        elif question_type == "date":
            attributes_list = attributes.split("@#@")
            question.min_value = datetime.strptime(attributes_list[0].strip(),"%d/%m/%Y")
            question.max_value = datetime.strptime(attributes_list[1].strip(),"%d/%m/%Y")
            question.start_value = datetime.strptime(attributes_list[2].strip(),"%d/%m/%Y")
        elif question_type == "text":
            attributes_list = attributes.split("@#@")
            question.max_no_characters = int(attributes_list[0])
        else:
            return
        question.save()
        dict = {"surveyID": surveyID}
        return HttpResponse(simplejson.dumps(dict), mimetype='application/javascript')
    return error_jump(request)
开发者ID:Copperfield,项目名称:ntusurvey,代码行数:94,代码来源:views.py


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