1、问卷的保存按钮
  前端通过ajax把数据发过来后端处理数据,然后返回给前端
2、对问卷做答
  首先用户进行登录,验证
  条件:1、只有本班的学生才能对问卷做答
       2、已经参加过的不能再次访问
      
在前端显示的样式
    显示当前问卷的问题

 分为(单选,多选,打分,文本)(多选未做)
    - 你对近期的工作有哪些意见、。?
      1 2 3 4 5 。。 10
    - 路宁女朋友一些建议?
            文本...
    - 路宁选择帽子颜色?
            A. 绿色    B.翠绿
            C. 墨绿    D.深绿色

问卷的保存按钮涉及到的知识点:
集合的操作:
   

1  s = [1,4,5,8]
2     s2 = [2,4,7,8,6]
3     print(set(s).difference(s2))  #做差集,在s中找和s2不同的元素  {1, 5}
4     print(set(s2).difference(s))  #做差集,在s2中找和s不同的元素  {2, 6, 7}
5     print(set(s)-set(s2))  #这种方式和上面的一样   {1, 5}
6     print(set(s2)^set(s))  #交集   {1, 2, 5, 6, 7}
7     print(set(s2)|set(s))   #并集  {1, 2, 4, 5, 6, 7, 8}

 

 1 # def outer():
 2 #     a=1
 3 #     def inner():
 4 #         for b in range(10):
 5 #             yield a
 6 #
 7 #     return inner()
 8 # for i in outer():
 9 #     print(i)
10 
11 
12 # class P:
13 #     pass
14 # print('type(P)---',type(P))
15 # print('P.__name__===',P.__name__)
16 #
17 # f = type('W',(object,),{})
18 # print('type(f)---',type(f))
19 # print('f.__name__===',f.__name__)
20 
21 
22 
23 # x = set('pwf')
24 # y = set('pwf123')
25 #
26 # print(y - x)  # {'2', '3', '1'}
27 # print(x - y)  # set()
28 
29 # l = []
30 # d =  {'option_1': '2', 'option_2': '4', 'val_3': '4', 'text_4': '123123123213213213213'}
31 # for k,v in d.items() :
32 #     # print('k',k,'v',v)
33 #     key,qid = k.rsplit('_',1)
34 #     # print(key,qid)
35 #     answer_dict = {'stu_id': id, 'que_id': qid, key: v}
36 #     print(answer_dict)
37 #     l.append(answer_dict)
38 # print(l)

 



 

进入正题:

表的设计:

from django.db import models

# Create your models here.
class UserInfo(models.Model):
    '''
    员工表
    '''
    name = models.CharField(max_length=12)
    password = models.CharField(max_length=32)

    def __str__(self):
        return self.name
class ClassList(models.Model):
    '''
    班级表
    '''
    title = models.CharField(max_length=32,verbose_name='班级名称')
    def __str__(self):
        return self.title
class Student(models.Model):
    '''
    道友表
    '''
    name = models.CharField(max_length=12,verbose_name='道友姓名')
    password = models.CharField(max_length=24,verbose_name='道友密码')
    classlist = models.ForeignKey(to=ClassList,verbose_name='道友所在班级')
    def __str__(self):
        return self.name
class QuestionNaire(models.Model):
    '''
    问卷表
    '''
    title = models.CharField(max_length=64,verbose_name='问卷标题')
    classlist = models.ForeignKey(to=ClassList,verbose_name='答问卷的班级')
    creator = models.ForeignKey(to=UserInfo,verbose_name='创建问卷的辣个银')
    def __str__(self):
        return self.title

class Question(models.Model):
    '''
    问题表
    '''
    caption = models.CharField(max_length=64,verbose_name='问题')
    question_type = (
        (1,'打分'),
        (2,'单选'),
        (3,'评价'),
    )
    tp = models.IntegerField(choices=question_type)
    questionnaire = models.ForeignKey(to=QuestionNaire,verbose_name='该问卷下的问题',default=1)
    def __str__(self):
       return self.caption


class Option(models.Model):
    '''
    单选题的选项
    '''
    option_name = models.CharField(max_length=32,verbose_name='选项名称')
    score = models.IntegerField(verbose_name='选项对应的分值')
    question = models.ForeignKey(to=Question,verbose_name='所在的问题')
    def __str__(self):
        return self.option_name

class Answer(models.Model):
    '''
    Answer my questions
    '''
    val = models.IntegerField(verbose_name='打分项的得分',null=True,blank=True)
    content = models.CharField(max_length=255,null=True,blank=True,verbose_name='评价')
    student = models.ForeignKey(to=Student,verbose_name='哪位道友答的题')
    question = models.ForeignKey(to=Question,verbose_name='答的是哪道题')
    option = models.ForeignKey(to=Option,verbose_name='单选选项',null=True)
    def __str__(self):
        return self.val

 

form相关:

  这里我们用到form & modelform来操作页面验证。

  需要注意的是: 这里添加问卷时,需要实时显示我们添加的东西哦。

  看代码:

 1 from django.forms import Form       #代表类的基类
 2 from django.forms import fields     #代表字段
 3 from django.forms import widgets    #插件
 4 from django.forms import ModelForm  #代表数据库和form可以一起用
 5 from app01 import models
 6 
 7 class QuestionNaire_Form(Form):
 8     '''添加页面的Form验证'''
 9     title = fields.CharField(required=True,max_length=64,
10                                 error_messages={
11                                     'required' : '问卷标题不可以为空!',
12                                     'max_length' : '超过最大长度'
13                                 },
14                                 widget=widgets.Textarea(attrs={'placeholder':'请输入问卷标题','type':'text','style':'width:80%;height:100px;','class':'form-control qn_title'}))
15 
16     classlist = fields.ChoiceField(required=True,initial=1,
17                                        error_messages={'required':'请选择班级'},widget=widgets.Select)
18 
19     # fields.RegexField()
20     # 实时更新问卷列表
21     def __init__(self,*args,**kwargs):
22         super(QuestionNaire_Form, self).__init__(*args,**kwargs)
23         self.fields['classlist'].choices = models.ClassList.objects.values_list("id","title")
24 
25 
26 
27 class QuestionModelForm(ModelForm):
28     class Meta:
29         model = models.Question
30         fields = ['caption','tp']     #这两行代表  拿到当前表所有的字段
31                                       #这个fields 是按照models里面写的字段格式在前端页面生成相应的东西.
32         widgets={'caption':widgets.Textarea(attrs={'style':'width:600px;height:80px','class':'form-control','placeholder':'请输入问题名称'})}
33 class OptionModelForm(ModelForm):
34     class Meta:
35         model = models.Option
36         fields = ['option_name','score']

 

然后进入到我们的views页面:

  1 """
  2 思路分析:
  3     拿到前端的数据,像下面这种格式的
  4     如果是json格式发的,注意要在request.body中取值。
  5      ajax_post_list = [
  6                 {
  7                     'id': 2,
  8                     'caption': "你到底爱不爱我??",
  9                     'tp': 1,
 10 
 11                 },
 12                 {
 13                     'id': None,
 14                     'caption': "你爱我什么?",
 15                     'tp': 3
 16                 },
 17                 {
 18                     'id': None,
 19                     'caption': "what do u say daring?",
 20                     'tp': 2,
 21                     "options": [
 22                         {'id': 1, 'name': '绿', 'score': 10},
 23                         {'id': 2, 'name': '翠绿', 'score': 8},
 24                     ]
 25                 },
 26             ]
 27     前端的数据和数据库的数据进行比较,
 28         - 前端有后端没有要添加
 29         - 前端没有后端有要删除
 30         - 前端有后端也有要更新
 31 """
 32 
 33 def eva_stu(request,class_id,qn_id):
 34 
 35     stu_obj = models.Student.objects.filter(id=request.session.get("stu_info").get("stu_id"),classlist_id=class_id).first()
 36 
 37     # 1. 先看是否是本班学生
 38     if not stu_obj:
 39         return HttpResponse('您不配啊!!!')
 40     # 2. 看它是否已经答过问卷
 41     ans_obj = models.Answer.objects.filter(student_id=stu_obj.id,question__questionnaire_id=qn_id).count()
 42     if ans_obj:
 43         return HttpResponse('别闹! 您已经答过了啊')
 44     # 3. 拿到所有的问题并显示
 45     from django.forms import Form,fields,widgets
 46     que_list = models.Question.objects.filter(questionnaire_id=qn_id).all()
 47     field_dict = {}
 48     for que in que_list:
 49         if que.tp == 1: # 打分用chioce
 50             field_dict['val_%s' % que.id] = fields.ChoiceField(
 51                 label = que.caption,
 52                 required=True,
 53                 error_messages={'required' : '不能为空哦'},
 54                 widget=widgets.RadioSelect,
 55                 choices=[ (i,i) for i in range(1,11) if i ]
 56             )
 57         elif que.tp == 2 : # 单选
 58             field_dict['option_%s' % que.id] = fields.ChoiceField(
 59                 required=True,
 60                 label = que.caption,
 61                 error_messages={'required':'必选'},
 62                 choices = models.Option.objects.filter(question_id=que.id).values_list('id','option_name'), #为什么改成values_list就可以显示选项
 63                 widget = widgets.RadioSelect
 64             )
 65         else :
 66             field_dict['text_%s' % que.id] = fields.CharField(
 67                 required=True,
 68                 label = que.caption,
 69                 widget = widgets.Textarea,
 70                 validators=[func,]
 71             )
 72     # print("field_dict",field_dict)
 73     # 创建类,并实例化
 74     # print('field_dict======',field_dict)
 75     MyAnswerForm = type('MyAnswerForm', (Form,),field_dict)
 76     if request.method == 'GET':
 77         form  = MyAnswerForm()
 78         return render(request,'eva_stu.html',{'form':form})
 79     else:
 80         form = MyAnswerForm(request.POST)
 81         if form.is_valid():
 82             print(form.cleaned_data)
 83             # {'option_1': '2', 'option_2': '4', 'val_3': '4', 'text_4': '123123123213213213213'}
 84             l = []
 85             for key,v in form.cleaned_data.items():
 86                 k,qid = key.rsplit('_',1)
 87                 answer_dict = {'student_id':stu_obj.id,'question_id':qid,k:v}
 88                 print(answer_dict)
 89                 # l1 = l.append(answer_dict)
 90                 l.append(models.Answer(**answer_dict))
 91                 print(77777)
 92                 # models.Answer.objects.bulk_create()
 93             return HttpResponse('ok')
 94         return render(request,'eva_stu.html',{'form':form})
 95 
 96 
 97 # 自定义form验证
 98 from django.core.exceptions import ValidationError
 99 def func(val):
100     if len(val) < 15 :
101         raise ValidationError(' duan duan duan ')

显示问卷内容并且拿到提交后的问卷答案