1、问卷的保存按钮
前端通过ajax把数据发过来后端处理数据,然后返回给前端
2、对问卷做答
首先用户进行登录,验证
条件:1、只有本班的学生才能对问卷做答
2、已经参加过的不能再次访问
在前端显示的样式
显示当前问卷的问题
分为(单选,多选,打分,文本)(多选未做)
- 你对近期的工作有哪些意见、。?
1 2 3 4 5 。。 10
- 路宁女朋友一些建议?
文本...
- 路宁选择帽子颜色?
A. 绿色 B.翠绿
C. 墨绿 D.深绿色
问卷的保存按钮涉及到的知识点:
集合的操作:
s = [1,4,5,8] s2 = [2,4,7,8,6] print(set(s).difference(s2)) #做差集,在s中找和s2不同的元素 {1, 5} print(set(s2).difference(s)) #做差集,在s2中找和s不同的元素 {2, 6, 7} print(set(s)-set(s2)) #这种方式和上面的一样 {1, 5} print(set(s2)^set(s)) #交集 {1, 2, 5, 6, 7} print(set(s2)|set(s)) #并集 {1, 2, 4, 5, 6, 7, 8}
# def outer(): # a=1 # def inner(): # for b in range(10): # yield a # # return inner() # for i in outer(): # print(i) # class P: # pass # print('type(P)---',type(P)) # print('P.__name__===',P.__name__) # # f = type('W',(object,),{}) # print('type(f)---',type(f)) # print('f.__name__===',f.__name__) # x = set('pwf') # y = set('pwf123') # # print(y - x) # {'2', '3', '1'} # print(x - y) # set() # l = [] # d = {'option_1': '2', 'option_2': '4', 'val_3': '4', 'text_4': '123123123213213213213'} # for k,v in d.items() : # # print('k',k,'v',v) # key,qid = k.rsplit('_',1) # # print(key,qid) # answer_dict = {'stu_id': id, 'que_id': qid, key: v} # print(answer_dict) # l.append(answer_dict) # 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来操作页面验证。
需要注意的是: 这里添加问卷时,需要实时显示我们添加的东西哦。
看代码:
from django.forms import Form #代表类的基类 from django.forms import fields #代表字段 from django.forms import widgets #插件 from django.forms import ModelForm #代表数据库和form可以一起用 from app01 import models class QuestionNaire_Form(Form): '''添加页面的Form验证''' title = fields.CharField(required=True,max_length=64, error_messages={ 'required' : '问卷标题不可以为空!', 'max_length' : '超过最大长度' }, widget=widgets.Textarea(attrs={'placeholder':'请输入问卷标题','type':'text','style':'width:80%;height:100px;','class':'form-control qn_title'})) classlist = fields.ChoiceField(required=True,initial=1, error_messages={'required':'请选择班级'},widget=widgets.Select) # fields.RegexField() # 实时更新问卷列表 def __init__(self,*args,**kwargs): super(QuestionNaire_Form, self).__init__(*args,**kwargs) self.fields['classlist'].choices = models.ClassList.objects.values_list("id","title") class QuestionModelForm(ModelForm): class Meta: model = models.Question fields = ['caption','tp'] #这两行代表 拿到当前表所有的字段 #这个fields 是按照models里面写的字段格式在前端页面生成相应的东西. widgets={'caption':widgets.Textarea(attrs={'style':'width:600px;height:80px','class':'form-control','placeholder':'请输入问题名称'})} class OptionModelForm(ModelForm): class Meta: model = models.Option fields = ['option_name','score']
然后进入到我们的views页面:
""" 思路分析: 拿到前端的数据,像下面这种格式的 如果是json格式发的,注意要在request.body中取值。 ajax_post_list = [ { 'id': 2, 'caption': "你到底爱不爱我??", 'tp': 1, }, { 'id': None, 'caption': "你爱我什么?", 'tp': 3 }, { 'id': None, 'caption': "what do u say daring?", 'tp': 2, "options": [ {'id': 1, 'name': '绿', 'score': 10}, {'id': 2, 'name': '翠绿', 'score': 8}, ] }, ] 前端的数据和数据库的数据进行比较, - 前端有后端没有要添加 - 前端没有后端有要删除 - 前端有后端也有要更新 """ def eva_stu(request,class_id,qn_id): stu_obj = models.Student.objects.filter(id=request.session.get("stu_info").get("stu_id"),classlist_id=class_id).first() # 1. 先看是否是本班学生 if not stu_obj: return HttpResponse('您不配啊!!!') # 2. 看它是否已经答过问卷 ans_obj = models.Answer.objects.filter(student_id=stu_obj.id,question__questionnaire_id=qn_id).count() if ans_obj: return HttpResponse('别闹! 您已经答过了啊') # 3. 拿到所有的问题并显示 from django.forms import Form,fields,widgets que_list = models.Question.objects.filter(questionnaire_id=qn_id).all() field_dict = {} for que in que_list: if que.tp == 1: # 打分用chioce field_dict['val_%s' % que.id] = fields.ChoiceField( label = que.caption, required=True, error_messages={'required' : '不能为空哦'}, widget=widgets.RadioSelect, choices=[ (i,i) for i in range(1,11) if i ] ) elif que.tp == 2 : # 单选 field_dict['option_%s' % que.id] = fields.ChoiceField( required=True, label = que.caption, error_messages={'required':'必选'}, choices = models.Option.objects.filter(question_id=que.id).values_list('id','option_name'), #为什么改成values_list就可以显示选项 widget = widgets.RadioSelect ) else : field_dict['text_%s' % que.id] = fields.CharField( required=True, label = que.caption, widget = widgets.Textarea, validators=[func,] ) # print("field_dict",field_dict) # 创建类,并实例化 # print('field_dict======',field_dict) MyAnswerForm = type('MyAnswerForm', (Form,),field_dict) if request.method == 'GET': form = MyAnswerForm() return render(request,'eva_stu.html',{'form':form}) else: form = MyAnswerForm(request.POST) if form.is_valid(): print(form.cleaned_data) # {'option_1': '2', 'option_2': '4', 'val_3': '4', 'text_4': '123123123213213213213'} l = [] for key,v in form.cleaned_data.items(): k,qid = key.rsplit('_',1) answer_dict = {'student_id':stu_obj.id,'question_id':qid,k:v} print(answer_dict) # l1 = l.append(answer_dict) l.append(models.Answer(**answer_dict)) print(77777) # models.Answer.objects.bulk_create() return HttpResponse('ok') return render(request,'eva_stu.html',{'form':form}) # 自定义form验证 from django.core.exceptions import ValidationError def func(val): if len(val) < 15 : raise ValidationError(' duan duan duan ')
显示问卷内容并且拿到提交后的问卷答案
end...