Example #1
0
def answer_detail(request,class_id, qid):
    student_id = request.session['student_info']['id']
    # 查看是否是当前问卷班级的学生
    class_check = models.Student.objects.filter(id=student_id, cls_id=class_id).count()
    if not class_check:
        return redirect("/login/")
    # 检查该用户是否提交过
    submit_check = models.Answer.objects.filter(stu_id=student_id, question__questionnaire_id=qid).count()
    if submit_check:
        return HttpResponse("你已经提交过了!")
    # 展示当前问卷的内容
    # 获取当前问卷的问题列表
    question_list = models.Question.objects.filter(questionnaire_id=qid)
    question_dict = {}
    for item in question_list:
        # 分别取出不同类型的问题
        if item.tp == 1:
            question_dict['val_%s' % item.id] = fields.ChoiceField(
                label=item.caption,
                error_messages={"required": "不能为空"},
                widget=widgets.RadioSelect,
                choices=[(i, i) for i in range(1, 11)]
            )
        elif item.tp == 2:
            question_dict['option_id_%s' % item.id] = fields.ChoiceField(
                label=item.caption,
                error_messages={"required": "不能为空"},
                widget=widgets.RadioSelect,
                choices=models.Option.objects.filter(qs_id=item.id).values_list("id", "name")
            )
        else:
            question_dict['content_%s' % item.id] = fields.CharField(
                label=item.caption,
                error_messages={"required":"不能为空"},
                widget=widgets.Textarea,
                # 调用func函数用来验证
                validators=([func, ])
            )
    # 通过type创建Form类,,可以循环的创建数据,question_dict为字段
    question_list_form = type("question_list_form", (Form,), question_dict)

    # 当get请求是,获取form对象,生成选项框
    if request.method == "GET":
        form = question_list_form()
        return render(request, "answer_detail.html", {"question_list": question_list, "form": form})
    else:
        # 验证用户提交的数据
        form = question_list_form(request.POST)
        answer_obj = []
        if form.is_valid():
            for k, v in form.cleaned_data.items():
                print(form.cleaned_data)
                t, qid = k.rsplit("_", 1)
                answer_dict = {"stu_id": student_id, "question_id": qid, t: v}
                answer_obj.append(models.Answer(**answer_dict))
            models.Answer.objects.bulk_create(answer_obj)
            return HttpResponse("感谢您的参与!")
        return render(request, "answer_detail.html", {"question_list": question_list, "form": form})
def answer(request,sur_id,cls_id):
    if not request.session.get("user"):
        return redirect("/login/")
    else:
        #不是此次答题班级的学生
        stud_list = models.Student.objects.filter(cls_id=cls_id,name=request.session["user"]["name"],password=request.session["user"]["password"])
        if not stud_list:
            return HttpResponse("你不是此次答题班级的学生,是不是想串班!!!")
        #答过题的学生,不能再次答!!
        answer_list = models.Answer.objects.filter(student_id=request.session["user"]["id"],question__surveyInfo_id=sur_id)
        if answer_list:
            return HttpResponse("你已经答过此次问卷,谢谢您的参与!!")
        #form组件#另一种生成form组件的形式,对象也是用type生成的
        question_list = models.Question.objects.filter(surveyInfo_id=sur_id)
        questions_dict = {}
        for question_obj in question_list:
            if question_obj.type == 1:
                questions_dict["option_id_%s"%question_obj.id]=fields.ChoiceField(label=question_obj.title,
                                                                                  choices=models.Option.objects.filter(qs_id=question_obj.id).values_list("id","score"),
                                                                        widget=wd.RadioSelect,
                                                                        error_messages={"required":"内容不能为空!"})
            elif question_obj.type == 2:
                questions_dict["score_%s"%question_obj.id]=fields.ChoiceField(label=question_obj.title,
                                                                              choices=[(i,i) for i in range(1,11)],
                                                                      widget=wd.RadioSelect,
                                                                      error_messages={"required": "内容不能为空!"})
            else:
                questions_dict["content_%s"%question_obj.id]=fields.CharField(label=question_obj.title,
                                                                              widget=wd.Textarea,
                                                                      error_messages={"required": "内容不能为空!"},
                                                                              validators=[func,])
        TestQuestion = type("Test", (Form,),questions_dict)
        if request.method == "GET":
            form = TestQuestion()
            return render(request,"answer.html",{"form":form})
        else:
            form = TestQuestion(request.POST)
            if not form.is_valid():
                return render(request, "answer.html", {"form": form})
            else:
                answer_l = []
                for key,v in form.cleaned_data.items():  #{'content_1': 'asdasdasdasdasdasdasdasdasd', 'score_2': '3', 'option_id_3': '8'}
                    field,ques_id = key.rsplit("_",1)
                    answer_dict = {'student_id':request.session["user"]["id"],"question_id":ques_id,field:v}
                    answer_l.append(models.Answer(**answer_dict))
                models.Answer.objects.bulk_create(answer_l)
                return HttpResponse("感谢您的参与!!我们献上诚挚的感谢")
Example #3
0
def score(request,class_id,qn_id):
    if not request.session.get("student_info"):
        return redirect("/student_login/")
    student_id = request.session["student_info"]["id"]
    #1,当前登录用户是否是要评论的班级学生
    ct1 = models.Student.objects.filter(id=student_id,classes_id=class_id).count()
    if not ct1:
        return HttpResponse("你只能评论自己班级的问卷")

    ct2 = models.Answer.objects.filter(student_id=student_id,question__Questionnaire_id=qn_id).count()

    if ct2:
        return HttpResponse("你已经参与过调查,无法再次进行")

    #展示当前问卷下的所有问题
    from django.forms import Form
    from django.forms import fields
    from django.forms import widgets

    question_list=models.Question.objects.filter(Questionnaire_id=qn_id)
    field_dict={}
    for que in question_list:
        if que.type == 1:
            field_dict['val_%s'%que.id]= fields.ChoiceField(
                label=que.name,
                error_messages={'required':'必填'},
                widget=widgets.RadioSelect,
                choices=[(i,i) for i in range(1,11)]
            )
        elif que.type == 2:
            field_dict['option_id_%s'%que.id]=fields.ChoiceField(
                label=que.name,
                widget=widgets.RadioSelect,
                choices=models.Option.objects.filter(
                    question_id=que.id).values_list("id","name"))
        else:
            from django.core.exceptions import ValidationError
            from django.core.validators import RegexValidator
            field_dict['content_%s'%que.id]=fields.CharField(
                label=que.name,widget=widgets.Textarea,validators=[func, ]
            )

    MyTestForm = type("MyTestForm",(Form,),field_dict)

    if request.method=="GET":
        form = MyTestForm()
        return render(request,"score.html",{'question_list':question_list,'form':form,"classId":class_id,"qn_id":qn_id})
    else:
        #15字验证
        #不允许为空
        form = MyTestForm(request.POST)
        print("requestpost里有哪些数据%s"%request.POST)
        if form.is_valid():
            print(form.cleaned_data)
            objs=[]
            for key,v in form.cleaned_data.items():
                k,qid=key.rsplit('_',1)
                print("k==%s v==%s"%(k,v))
                answer_dict={'student_id':student_id,'question_id':qid,k:v}
                objs.append(models.Answer(**answer_dict))
            models.Answer.objects.bulk_create(objs)
            return HttpResponse("感谢您的参与!!!")
        return render(request,"score.html",{'question_list':question_list,'form':form})
Example #4
0
def show(request, class_id, naire_id):
    '''
    投放问卷页面
    '''
    if not request.session.get('userinfo').get('role') == '学生':
        return redirect('/logout/?ReturnURL=' + request.path_info)

    # 对当前URL进行校验############################
    if not models.ClassRoom.objects.filter(id=class_id).exists():
        # 如果url中的班级id不存在
        return render(request, 'not found.html')
    elif not models.Questionnaire.objects.filter(id=naire_id).exists():
        # 如果url中的问卷id不存在
        return render(request, 'not found.html')

    # 对当前打开问卷页面的用户进行校验##############
    session_dict = request.session.get('userinfo')
    user_class_id = session_dict.get('class_id')
    if user_class_id != int(class_id):
        return render(request, 'not found.html', {"warning": "不是本班学生不能填写问卷!"})

    stu_id = session_dict.get('stu_id')
    if models.Answer.objects.filter(student_id=stu_id).exists():
        return render(request, 'not found.html', {"warning": '已经填写过此问卷!'})

    # 动态生成Form组件#############################
    def my_valid(text):
        '''自定义验证规则'''
        if len(text) < 15:
            raise ValidationError('内容不能少于十五字')

    question_list = models.Question.objects.filter(questionnaire_id=naire_id)
    form_dict = {}

    for que_obj in question_list:
        if que_obj.type == 1:
            form_dict['value_%s' % que_obj.id] = fields.ChoiceField(
                label=que_obj.title,
                widget=widgets.RadioSelect,
                choices=[(i, i) for i in range(1, 11)],
                error_messages={"required": '不能为空'},
            )
        elif que_obj.type == 2:
            form_dict['option_id_%s' % que_obj.id] = fields.ChoiceField(
                label=que_obj.title,
                widget=widgets.RadioSelect,
                choices=models.Option.objects.filter(
                    question=que_obj).values_list('value', 'content'),
                error_messages={"required": '不能为空'},
            )
        else:
            form_dict['content_%s' % que_obj.id] = fields.CharField(
                label=que_obj.title,
                widget=widgets.Textarea,
                error_messages={"required": '不能为空'},
                validators=(my_valid, ),
            )

    ShowForm = type("ShowForm", (Form, ), form_dict)  # 动态创建一个Form类

    # 处理HTTP请求################################
    if request.method == 'GET':
        show_form = ShowForm()
        return render(request, 'show.html', {"show_form": show_form})
    else:
        show_form = ShowForm(request.POST)
        if not show_form.is_valid():
            return render(request, 'show.html', {"show_form": show_form})
        else:
            # print(show_form.cleaned_data)
            bulk_obj_list = []
            for k, v in show_form.cleaned_data.items():
                col, qid = k.rsplit('_', 1)
                answer_dict = {
                    "question_id": qid,
                    "student_id": stu_id,
                    col: v
                }
                bulk_obj_list.append(models.Answer(**answer_dict))
            models.Answer.objects.bulk_create(bulk_obj_list)
        return HttpResponse('感谢参与本次问卷调查!')
def fill_naire(request, class_id, naire_id):
    if not request.session["student_info"].get("stu_id"):
        return redirect("/stu_login/")
    student_id = request.session["student_info"].get("stu_id")
    s1 = models.Student.objects.filter(id=student_id, cls_id=class_id).count()
    if not s1:  # 判断是否是本次问卷班级的学生
        return HttpResponse("你只能填写你所在班级的问卷")
    s2 = models.Answer.objects.filter(
        student_id=student_id, question__questionnaire_id=naire_id).count()
    if s2:  # 判断是否已经提交过了
        return HttpResponse("你已经填写过了")

    # 所有判断都通过的情况下就显示当前问卷的问题
    from django.forms import widgets, Form, fields
    question_list = models.Question.objects.filter(questionnaire_id=naire_id)
    fields_dic = {}  # 创建一个字典用来存字段
    for question in question_list:
        if question.type == 1:
            fields_dic['val_%s' % question.id] = fields.ChoiceField(
                choices=[(i, i) for i in range(1, 11)],
                widget=widgets.RadioSelect(),
                label=question.caption,
                error_messages={"required": "此字段补不能为空"})
        elif question.type == 2:
            fields_dic['oid_%s' % question.id] = fields.ChoiceField(
                choices=models.Option.objects.filter(
                    question_id=question.id).values_list("id", "name"),
                widget=widgets.RadioSelect(),
                label=question.caption,
                error_messages={"required": "此字段补不能为空"})
        elif question.type == 3:
            fields_dic['content_%s' % question.id] = fields.CharField(
                widget=widgets.Textarea(attrs={
                    "rows": "5",
                    "cols": "80"
                }),
                validators=[
                    func,
                ],
                label=question.caption,
                error_messages={"required": "此字段补不能为空"})

    MytestForm = type("MytestForm", (Form, ), fields_dic)

    if request.method == "GET":
        form = MytestForm()

    else:
        print(request.POST)
        form = MytestForm(request.POST)
        if form.is_valid():
            objs = []
            for i, v in form.cleaned_data.items():
                name, id = i.split('_', 1)
                answer_dic = {
                    "student_id": student_id,
                    "question_id": id,
                    name: v
                }
                obj = models.Answer(**answer_dic)
                objs.append(obj)
            models.Answer.objects.bulk_create(objs)
            return HttpResponse("你已成功提交,感谢的你反馈")

    return render(request, "question_naire.html", {"forms": form})
Example #6
0
def score(request, class_id, qn_id):
    """
    :param request:
    :param class_id: 班级ID
    :param qn_id: 问卷ID
    :return:
    """
    student_id = request.session['student_info']['id']
    # 1. 当前登录用户是否是要评论的班级的学生
    ct1 = models.Student.objects.filter(id=student_id, cls_id=class_id).count()
    if not ct1:
        return HttpResponse('你只能评论自己班级的问卷,是不是想转班?')

    # 2. 你是否已经提交过当前问卷答案
    ct2 = models.Answer.objects.filter(stu_id=student_id,
                                       question__naire_id=qn_id).count()
    if ct2:
        return HttpResponse('你已经参与过调查,无法再次进行')

    # 3. 展示当前问卷下的所有问题
    # question_list = models.Question.objects.filter(naire_id=qn_id)

    from django.forms import Form
    from django.forms import fields
    from django.forms import widgets

    # # 类:方式一
    # class TestForm(Form):
    #     tp1 = fields.ChoiceField(label='路宁傻不傻?',choices=[ (i,i) for i in range(1,11)],widget=widgets.RadioSelect)
    #     tp2 = fields.ChoiceField(label='路宁傻不傻?',choices=[ (i,i) for i in range(1,11)],widget=widgets.RadioSelect)
    #     tp3 = fields.CharField(label='对路宁的建议?',widget=widgets.Textarea)
    #     tp4 = fields.ChoiceField(label='路宁帽子颜色?',choices=[ (i,i) for i in range(1,11)],widget=widgets.RadioSelect)
    #
    # # 类:方式二
    # MyTestForm = type("MyTestForm",(Form,),{
    #     'tp1': fields.ChoiceField(label='路宁傻不傻?',choices=[ (i,i) for i in range(1,11)],widget=widgets.RadioSelect),
    #     'tp2': fields.ChoiceField(label='路宁傻不傻?',choices=[ (i,i) for i in range(1,11)],widget=widgets.RadioSelect),
    #     'tp3': fields.CharField(label='对路宁的建议?',widget=widgets.Textarea),
    #     'tp4': fields.ChoiceField(label='路宁帽子颜色?',choices=[ (i,i) for i in range(1,11)],widget=widgets.RadioSelect),
    # })
    # return render(request,'score.html',{'question_list':question_list,'form':MyTestForm()})
    question_list = models.Question.objects.filter(naire_id=qn_id)
    field_dict = {}
    for que in question_list:
        if que.tp == 1:
            field_dict['val_%s' % que.id] = fields.ChoiceField(
                label=que.caption,
                error_messages={'required': '必填'},
                widget=widgets.RadioSelect,
                choices=[(i, i) for i in range(1, 11)])
        elif que.tp == 2:
            field_dict['option_id_%s' % que.id] = fields.ChoiceField(
                label=que.caption,
                widget=widgets.RadioSelect,
                choices=models.Option.objects.filter(qs_id=que.id).values_list(
                    'id', 'name'))
        else:
            from django.core.exceptions import ValidationError
            from django.core.validators import RegexValidator
            # field_dict['x_%s' % que.id] = fields.CharField(
            #     label=que.caption, widget=widgets.Textarea,validators=[RegexValidator(regex=""),])
            field_dict['content_%s' % que.id] = fields.CharField(
                label=que.caption,
                widget=widgets.Textarea,
                validators=[
                    func,
                ])
    # 类:方式二
    MyTestForm = type("MyTestForm", (Form, ), field_dict)

    if request.method == 'GET':
        form = MyTestForm()
        return render(request, 'score.html', {
            'question_list': question_list,
            'form': form
        })
    else:
        # 15字验证
        # 不允许为空
        form = MyTestForm(request.POST)
        if form.is_valid():
            print(form.cleaned_data)
            # {'x_2': '3', 'x_9': 'sdfasdfasdfasdfasdfasdfasdf', 'x_10': '13'}
            objs = []
            for key, v in form.cleaned_data.items():
                k, qid = key.rsplit('_', 1)
                answer_dict = {'stu_id': student_id, 'question_id': qid, k: v}
                objs.append(models.Answer(**answer_dict))
            models.Answer.objects.bulk_create(objs)
            return HttpResponse('感谢您的参与!!!')

        return render(request, 'score.html', {
            'question_list': question_list,
            'form': form
        })
Example #7
0
def score(request, q_id, c_id):
    '''
    问卷里的问题————回答
    :param request:
    :param q_id:
    :param c_id:
    :return:
    '''
    stu_id = request.session.get("user_id")  #从session中取出当前登录用户的id
    if not stu_id:
        return redirect("/login/")

    #判断当前登录的用户是否需要答卷的班级的学生
    stu_obj = models.Student.objects.filter(id=stu_id, cls_id=c_id).count()
    if not stu_obj:
        return HttpResponse("对不起,您不是本次调查的对象")

    #判断是否已经提交过问卷答案
    has_join = models.Answer.objects.filter(stu_id=stu_id,
                                            question__naire_id=q_id)
    if has_join:
        return HttpResponse("对不起,您已经参与本次问卷,不可重复参与")

    #获取当前问卷的所有问题
    question_list = models.Question.objects.filter(naire_id=q_id)
    field_dict = {}  #设一个空字典
    for que in question_list:  #for 循环取出所有问题
        if que.tp == 1:  #如果等于打分类型。
            field_dict["val_%s" % que.id] = fields.ChoiceField(
                label=que.caption,  #标题
                error_messages={"required": "必填"},  #提示错误
                widget=widgets.RadioSelect,  #单选圆点
                choices=[(i, i) for i in range(1, 11)]  #循环1-11
            )
        elif que.tp == 2:
            field_dict["option_id_%s" % que.id] = fields.ChoiceField(
                label=que.caption,  #标题
                error_messages={"required": "必填"},  #错误提示
                widget=widgets.RadioSelect,  #单选圆点
                #这里数据表option中的score是不需要给用户看到的
                choices=models.Option.objects.filter(qs_id=que.id).values_list(
                    "id", "name")  #按需求取需要的值
            )
        else:
            field_dict["content_%s" % que.id] = fields.CharField(
                label=que.caption,  #标题
                error_messages={"required": "必填"},  #错误提示
                widget=widgets.Textarea(attrs={
                    "class": "form-control",
                    "rows": "2",
                    "cols": "60"
                }),  #输入文本框
                validators=[
                    func,
                ]  #这里可以写正则,也可以自定义函数放在这里
            )
    myForm = type("myTestForm", (Form, ), field_dict)  #动态生成类,参数分别是类名,继承的对象,字段

    if request.method == "GET":
        form = myForm()  #实例化
        return render(request, "score.html", {
            "question_list": question_list,
            "form": form
        })
    else:
        form = myForm(request.POST)
        if form.is_valid():  #验证成功
            obj_list = []  #设个空立标
            for key, v in form.cleaned_data.items():  #  for 循环干净数据。
                print('zzzzzzzzzzzzzzzzzzzzz', key, v)  # val_5  2
                key, qid = key.rsplit("_", 1)  #从右边切,切一次
                print(key, qid)  #val 5
                answer_dict = {
                    "stu_id": stu_id,
                    "question_id": qid,
                    key: v
                }  #上面切分成根数据库对应的格式,以便我们保存。
                print(answer_dict)
                obj_list.append(models.Answer(**answer_dict))
            models.Answer.objects.bulk_create(obj_list)  #批量插入
            return HttpResponse("感谢您的参与")
        return render(request, "score.html", {
            "question_list": question_list,
            "form": form
        })