使用Django開發一個選擇題系統


  使用Django+MySQL開發一個選擇題系統,選擇題有題干,對應選項,對應答案幾項內容

  一,創建Django項目

 

 

 

 

   創建成功

 

 

   修改配置

 

 

   數據庫配置

  數據庫需要先創建好

> create database health;

  

 'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'health',
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': '192.168.1.188',
        'PORT': '3306',
        'OPTIONS': {
            "init_command": "SET sql_mode='STRICT_TRANS_TABLES'",
        }
    }

  時區配置

 

   靜態資源配置

 

   靜態文件夾static需要手動創建和模板templates同路徑在項目health之下

 

   MySQL模塊支持配置

  配置在app subject之下即題目表下

 

   二,數據庫模板設計

  題目表有3個表,分別為題目表,以及題目對應的選項表和答案表,結構如下

  題目選項表和答案表分別關聯題目表的主鍵id

 

   模板設計

 

from django.db import models

Type = (
    (0, '單選'),
    (1, '多選')
)

Option = (
    (1, 'A'),
    (2, 'B'),
    (3, 'C'),
    (4, 'D'),
    (5, 'E'),
    (6, 'F'),
    (7, 'G'),
    (8, 'H'),
)

# Create your models here.
class Subject(models.Model):
    stem = models.CharField(max_length=1024, verbose_name='題干內容', blank=False, null=False)
    type = models.IntegerField(choices=Type, verbose_name='題目類型,單選還是多選')
    explain = models.CharField(max_length=512, verbose_name='題目答案解析', blank=False, null=False)

    class Meta:
        db_table = 'subject'
        verbose_name = '題干表'

class Options(models.Model):
    options = models.IntegerField(choices=Option, verbose_name='選項ABCDEFGH')
    content = models.CharField(max_length=256, verbose_name='選項內容')
    subject = models.ForeignKey('Subject')

    class Meta:
        db_table = 'options'
        verbose_name = '選項表'
        unique_together = ('subject', 'content')
        ordering = ['options']

class Answer(models.Model):
    options = models.IntegerField(choices=Option, verbose_name='選項ABCDEFGH')
    subject = models.ForeignKey('Subject')

    class Meta:
        db_table = 'answer'
        verbose_name = '答案表'
        unique_together = ('subject', 'options')
        ordering = ['options']

  這里題目類型對應的類型為choices即數字0對應單選數字1對應多選

  選項表也是12345678分別對應選項ABCDEFGH

  數據遷移

  注意運行數據遷移命令的路徑是在項目文件夾下

D:\health>python manage.py makemigrations subject
D:\health>python manage.py migrate subject

  登錄數據庫查看創建的表

 

 

 

   插入數據

   示例題目內容如下

題目
人類心理現象包括
選項
A , 心理活動過程 
B , 個性心理特征 
C , 認知、情感和意志力 
D , 心理活動過程和個性心理特征 
E , 感覺功能、運動功能、聯絡功能系統 
解析
人的心理現象包括心理過程和個性心理。 心理過程包括認識教程、情結與情感過程、意志教程三個相互聯系的方面。 個性心理特征包括人的能力、氣質、性格。具體表現在人的個性傾向性、個性心理特征和自我意識三個方面
答案
答案 D

  首先插入題目和解析

mysql> insert into subject values(null,'人類心理現象包括',0,'人的心理現象包括心理過程和個性心理。 心理過程包括認識教程、情結與情感過程、意志教程三個相互聯系的方面。 個性心理特征包括人的能力、氣質、性格。具 體表現在人的個性傾向性、個性心理特征和自我意識三個方面');

  id自增,題目為單選題

  插入選項

mysql> insert into options values(null,1,'心理活動過程',1);
Query OK, 1 row affected (0.00 sec)

mysql> insert into options values(null,2,'個性心理特征',1);
Query OK, 1 row affected (0.00 sec)

mysql> insert into options values(null,3,'認知,情感和意志力',1);
Query OK, 1 row affected (0.00 sec)

mysql> insert into options values(null,4,'心理活動過程和個性心理特征',1);
Query OK, 1 row affected (0.00 sec)

mysql> insert into options values(null,5,'感覺功能、運動功能、聯絡功能系統',1);
Query OK, 1 row affected (0.00 sec)

  插入答案

mysql> insert into answer values(null,4,1);
Query OK, 1 row affected (0.00 sec)

  查看數據庫

   三,在web頁面展示數據

  ①設置路由

 

 

 

   ②視圖

 

   ③模板

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>健康管理師練習題</title>
</head>
<body>
{#    遍歷數據庫提取所有題目#}
    {% for one in object_list %}
{#        顯示題目題干 forloop.counter為顯示序號 #}
        <p>{{ forloop.counter }}, {{ one.stem }}</p>
{#        顯示選項以及對應選項的內容get_options_display為把選項1234顯示成ABCD#}
        {% for options in one.options_set.all %}
            {{ options.get_options_display }}, {{ options.content }} </br>
        {% endfor %}
{#        顯示答案get_options_display為把選項1234顯示成ABCD#}
        {% for answer in one.answer_set.all %}
            {{ answer.get_options_display }}
        {% endfor %}
    {% endfor %}
</body>
</html>

  web頁面查看

 

   把答案和解析做成隱藏然后使用按鍵顯示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>健康管理師練習題</title>
</head>
<body>
{#    遍歷數據庫提取所有題目#}
    {% for one in object_list %}
{#        顯示題目題干 forloop.counter為顯示序號 #}
        <p>{{ forloop.counter }}, {{ one.stem }}</p>
{#        顯示選項以及對應選項的內容get_options_display為把選項1234顯示成ABCD#}
        {% for options in one.options_set.all %}
            {{ options.get_options_display }}, {{ options.content }} </br>
        {% endfor %}
{#        顯示答案get_options_display為把選項1234顯示成ABCD#}
        <p id="{{ one.id }}id" hidden>
        {% for answer in one.answer_set.all %}
            {{ answer.get_options_display }}
        {% endfor %}
        </p>
        <input type = 'button' onclick=showp("{{ one.id }}id") value='答案'/>
        <p id="{{ one.id }}explain" hidden>{{ one.explain }}</p>
        <input type = 'button' onclick=showp("{{ one.id }}explain") value='解析'>
    {% endfor %}
<script>
    {#隱藏顯示函數#}
    function showp(id){
        if (document.getElementById(id).style.display == 'inline') {
            document.getElementById(id).style.display = 'none';
        }
        else {
            document.getElementById(id).style.display='inline';
        }

    }
</script>
</body>
</html>

  把答案和解析先隱藏,添加按鈕,如果答案是隱藏的則點擊按鈕顯示答案如果答案是顯示的則點擊按鈕隱藏答案,解析也是如此

  這里把答案和解析包含在一個p標簽內,id分別為使用one.id加字符串id拼接的即類似於1id 1explain的id這樣保證每個p標簽的id不重復並且在id內不會出現一些特殊字符導致id不可用的問題

  頁面顯示

 

 

   四,添加數據

  ①路由

 

 

   ②視圖

 

 

 

class SubjectAddView(TemplateView):
    template_name = 'subject_add.html'
    def post(self, request):
        data = request.POST
        res = {'status': 0, 'msg': '添加成功'}
        try:
            subject = Subject()
            subject.stem = data.get('stem')
            subject.explain = data.get('explain')
            subject.type = data.get('type')
            print(data.getlist('option'))
            print(data.getlist('content'))
            print(data.getlist('explain'))
            print(data.getlist('answer'))
            subject.save()
            for one in data.getlist('option'):
                options = Options()
                options.subject_id = subject.id

                options.options = one
                options.content = data.getlist('content')[int(one)-1]
                options.save()
            for one in data.getlist('answer'):
                answer = Answer()
                answer.subject_id = subject.id
                answer.options = one
                answer.save()
        except Exception as e:
            print(e)
            res = {'status': 1, 'msg': '添加失敗'}
        return JsonResponse(res)

  ③模板

 

 

   注意需要加載css js

<!DOCTYPE html>
<html lang="ch">
<head>
    <meta charset="UTF-8">
    <title>添加題目</title>

{#    <link href="/static/css/bootstrap.min.css" rel="stylesheet">#}
    <link href="/static/font-awesome/css/font-awesome.css" rel="stylesheet">
    <link href="/static/css/plugins/toastr/toastr.min.css" rel="stylesheet">
     <link href="/static/css/plugins/sweetalert/sweetalert.css" rel="stylesheet">
{#    <link href="/static/css/animate.css" rel="stylesheet">#}
{#    <link href="/static/css/style.css" rel="stylesheet">#}

</head>
<body>
 <div class="ibox-content">
        <form id="submit_form" class="form-horizontal">
            {% csrf_token %}
            <div ><label class="col-sm-2 control-label">題目內容</label>
                <div class="col-sm-6"><input type="text"  maxlength="512" size="100" name="stem" required></div>
            </div>

              <div ><label class="col-sm-2 control-label">題目解析</label>
{#                <div ><input type="text"maxlength="512" size="100" name="explain"></div>#}
                  <div> <textarea name="explain" cols="30" rows="10"> </textarea></div>
            </div>
            題目類型:<input type="radio" name="type" value="0" checked/>  單選 <input type="radio" name="type" value="1" /> 多選 <br/>
            <div class="form-group"><label class="col-sm-2 control-label">選項</label>
                <div ><input type="checkbox"  name="option" value=1 checked > A <input type="text"  name="content" required></div>
                <div ><input type="checkbox"  name="option" value=2 checked > B <input type="text" class="" name="content"></div>
                <div ><input type="checkbox"  name="option" value=3 checked > C <input type="text" class="" name="content"></div>
                <div ><input type="checkbox"  name="option" value=4 checked > D <input type="text" class="" name="content"></div>
                <div ><input type="checkbox"  name="option" value=5> E <input type="text" class="" name="content"> </div>
                <div ><input type="checkbox"  name="option" value=6> F <input type="text" class="" name="content"> </div>
                <div ><input type="checkbox"  name="option" value=7> G <input type="text" class="f" name="content"> </div>
                <div ><input type="checkbox"  name="option" value=8> H <input type="text" class="" name="content"> </div>
                <div ><input type="checkbox"  name="option" value=9> I <input type="text" class="" name="content"> </div>
            </div>
            <div class="form-group"><label class="col-sm-2 control-label">答案</label>
                <div class="col-sm-6"><input type="checkbox" class="" name="answer" value=1> A </div>
                <div class="col-sm-6"><input type="checkbox" class="" name="answer" value=2> B </div>
                <div class="col-sm-6"><input type="checkbox" class="" name="answer" value=3> C </div>
                <div class="col-sm-6"><input type="checkbox" class="" name="answer" value=4> D </div>
                <div class="col-sm-6"><input type="checkbox" class="" name="answer" value=5> E </div>
                <div class="col-sm-6"><input type="checkbox" class="" name="answer" value=6> F </div>
                <div class="col-sm-6"><input type="checkbox" class="" name="answer" value=7> G </div>
                <div class="col-sm-6"><input type="checkbox" class="" name="answer" value=8> H </div>
                <div class="col-sm-6"><input type="checkbox" class="" name="answer" value=9> I </div>
            </div>

                <div class="">
{#                    <a class="btn btn-white" type="submit" href="javascript:history.back(-1)">取消</a>#}
                    <button class="btn btn-primary" type="submit">保存更改</button>
                </div>

        </form>
    </div>
    <script src="/static/js/jquery-3.1.1.min.js"></script>
    <script src="/static/js/bootstrap.min.js"></script>
    <script src="/static/js/plugins/metisMenu/jquery.metisMenu.js"></script>
    <script src="/static/js/plugins/slimscroll/jquery.slimscroll.min.js"></script>
    <script src="/static/js/plugins/validate/jquery.validate.js"></script>
    <script src="/static/js/plugins/validate/messages_zh.js"></script>
    <script src="/static/js/plugins/sweetalert/sweetalert.min.js"></script>
    <script src="/static/js/inspinia.js"></script>
    <script src="/static/js/plugins/pace/pace.min.js"></script>

    <script>
        $(document).ready(function () {
            $("#submit_form").validate({
             submitHandler: function () {
                    var str = $('#submit_form').serialize();
                    $.post('{% url 'subject_add' %}', str, function (res) {
                        if (res.status == 0) {
                            swal({
                                title: res.msg,
                                type: 'success',
                                confirmButtonText: "確定"
                            },
                               function () {
                               window.location.href = '{% url 'index' %}';
                            });
                        } else {
                            swal({
                                title: res.msg,
                                type: 'error',
                                confirmButtonText: "確定"
                            });
                        }
                    });
                }
            });
        });
    </script>
</body>
</html>

  首頁增加一個跳轉按鈕至添加數據

 

 

 

 

 

 

 

 

 

 

  代碼解析

 

   五,更新數據

  ①路由

 

 

 url(r'^update', SubjectUpdateView.as_view(), name='subject_update'),

  ②視圖

 

 

class SubjectUpdateView(View):
    def get(self, request):
        return render(request, 'subject_update.html', {'subject_obj': Subject.objects.get(id=request.GET.get('id'))})

    def post(self, request):
        data = request.POST
        res = {'status': 0, 'msg': '修改成功'}
        try:
            subject = Subject.objects.get(id=data.get('uid'))
            print(subject)
            subject.stem = data.get('stem')
            subject.explain = data.get('explain')
            subject.type = data.get('type')
            print(data.getlist('option'))
            print(data.getlist('content'))
            print(data.getlist('answer'))
            subject.save()
            Options.objects.filter(subject_id=data.get('uid')).delete()
            for one in data.getlist('option'):
                options = Options()
                options.subject_id = subject.id
                options.options = one
                options.content = data.getlist('content')[int(one)-1]
                options.save()
            Answer.objects.filter(subject_id=data.get('uid')).delete()
            for one in data.getlist('answer'):
                answer = Answer()
                answer.subject_id = subject.id
                answer.options = one
                answer.save()
        except Exception as e:
            print(e)
            res = {'status': 1, 'msg': '修改失敗'}
        return JsonResponse(res)

  代碼解析

  更新數據和添加數據類似,不過是需要把原來數據庫中已經存在的數據傳遞到頁面,只修改需要修改的地方

  ③模板

 

 

<!DOCTYPE html>
<html lang="ch">
<head>
    <meta charset="UTF-8">
    <title>添加題目</title>
{#    <link href="/static/css/bootstrap.min.css" rel="stylesheet">#}
    <link href="/static/font-awesome/css/font-awesome.css" rel="stylesheet">
    <link href="/static/css/plugins/toastr/toastr.min.css" rel="stylesheet">
      <link href="/static/css/plugins/sweetalert/sweetalert.css" rel="stylesheet">
{#    <link href="/static/css/animate.css" rel="stylesheet">#}
{#    <link href="/static/css/style.css" rel="stylesheet">#}

</head>
<body>
 <div class="ibox-content">
        <form id="submit_form" class="form-horizontal">
            {% csrf_token %}
            <h1> 更新題目 {{ subject_obj.id }}</h1>
            <div class="form-group"><label class="col-sm-2 control-label">題目內容</label>
                <div class="col-sm-6"><input type="text" class="form-control" maxlength="512" size="100" name="stem" value="{{ subject_obj.stem }}" required></div>
            </div>
            <div class="hr-line-dashed"></div>
              <div class="form-group"><label class="col-sm-2 control-label">題目解析</label>
{#                <div class="col-sm-6"><input type="text" class="form-control" maxlength="512" size="100" name="explain" value="{{ subject_obj.explain }}"></div>#}
                  <div> <textarea name="explain" cols="30" rows="10" >{{ subject_obj.explain }} </textarea></div>
            </div>
            題目類型:<input type="radio" name="type" value="0" checked/>  單選 <input type="radio" name="type" value="1" /> 多選 <br/>
            <div class="form-group"><label class="col-sm-2 control-label">選項</label>
                {% for options in subject_obj.options_set.all %}
                   {% if options.options == 1 %}
                       <div class="col-sm-6"><input type="checkbox" class="form-control" name="option" value=1 checked > A <input type="text" class="form-control" name="content" value="{{ options.content }}"></div>
                       {% elif options.options == 2 %}
                        <div class="col-sm-6"><input type="checkbox" class="form-control" name="option" value=2 checked > B <input type="text" class="form-control" name="content" value="{{ options.content }}"></div>
                        {% elif options.options == 3 %}
                        <div class="col-sm-6"><input type="checkbox" class="form-control" name="option" value=3 checked > C <input type="text" class="form-control" name="content" value="{{ options.content }}"></div>
                        {% elif options.options == 4 %}
                        <div class="col-sm-6"><input type="checkbox" class="form-control" name="option" value=4 checked > D <input type="text" class="form-control" name="content" value="{{ options.content }}"></div>
                        {% elif options.options == 5 %}
                        <div class="col-sm-6"><input type="checkbox" class="form-control" name="option" value=5 checked > E <input type="text" class="form-control" name="content" value="{{ options.content }}"></div>
                        {% elif options.options == 6 %}
                        <div class="col-sm-6"><input type="checkbox" class="form-control" name="option" value=6 checked > F <input type="text" class="form-control" name="content" value="{{ options.content }}"></div>
                        {% elif options.options == 7 %}
                        <div class="col-sm-6"><input type="checkbox" class="form-control" name="option" value=7 checked > G <input type="text" class="form-control" name="content" value="{{ options.content }}"></div>
                        {% elif options.options == 8 %}
                        <div class="col-sm-6"><input type="checkbox" class="form-control" name="option" value=8 checked > H <input type="text" class="form-control" name="content" value="{{ options.content }}"></div>
                        {% elif options.options == 9 %}
                        <div class="col-sm-6"><input type="checkbox" class="form-control" name="option" value=9 checked > I <input type="text" class="form-control" name="content" value="{{ options.content }}"></div>
                   {% endif %}
                {% endfor%}


            </div>
            <div class="form-group"><label class="col-sm-2 control-label">答案</label>
                <div class="col-sm-6"><input type="checkbox" class="form-control" name="answer" value=1> A </div>
                <div class="col-sm-6"><input type="checkbox" class="form-control" name="answer" value=2> B </div>
                <div class="col-sm-6"><input type="checkbox" class="form-control" name="answer" value=3> C </div>
                <div class="col-sm-6"><input type="checkbox" class="form-control" name="answer" value=4> D </div>
                <div class="col-sm-6"><input type="checkbox" class="form-control" name="answer" value=5> E </div>
                <div class="col-sm-6"><input type="checkbox" class="form-control" name="answer" value=6> F </div>
                <div class="col-sm-6"><input type="checkbox" class="form-control" name="answer" value=7> G </div>
                <div class="col-sm-6"><input type="checkbox" class="form-control" name="answer" value=8> H </div>
                <div class="col-sm-6"><input type="checkbox" class="form-control" name="answer" value=9> I </div>
            </div>

            <div class="hr-line-dashed"></div>
            <div class="form-group">
                <div class="col-sm-4 col-sm-offset-2">
                     <input hidden value="{{ subject_obj.id }}" name="uid">
{#                    <a class="btn btn-white" type="submit" href="javascript:history.back(-1)">取消</a>#}
                    <button class="btn btn-primary" type="submit">保存更改</button>
                </div>
            </div>
        </form>
    </div>
    <script src="/static/js/jquery-3.1.1.min.js"></script>
    <script src="/static/js/bootstrap.min.js"></script>
    <script src="/static/js/plugins/metisMenu/jquery.metisMenu.js"></script>
    <script src="/static/js/plugins/slimscroll/jquery.slimscroll.min.js"></script>
    <script src="/static/js/plugins/validate/jquery.validate.js"></script>
    <script src="/static/js/plugins/validate/messages_zh.js"></script>
    <script src="/static/js/plugins/sweetalert/sweetalert.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#submit_form").validate({
                rules: {
                    name_cn: {
                        required: true
                    },
                    username: {
                        required: true
                    },
                    email: {
                        required: true
                    },
                    password: {
                        required: true
                    },
                    phone: {
                        required: true,
                        minlength:11
                    },
                    wechat: {
                        required: true
                    }
                }, submitHandler: function () {
                    var str = $('#submit_form').serialize();
                    $.post('{% url 'subject_update' %}', str, function (res) {
                        if (res.status == 0) {
                            swal({
                                title: res.msg,
                                type: 'success',
                                confirmButtonText: "確定"
                            }, function () {
                                window.location.href = '{% url 'index' %}';
                            });
                        } else {
                            swal({
                                title: res.msg,
                                type: 'error',
                                confirmButtonText: "確定"
                            });
                        }
                    });
                }
            });
        });
    </script>
</body>
</html>

  注意:本次有bug 例如更新數據只能更新原有選項一樣多的數量選項,不能添加選項,答案沒有按原有答案選中,需要重新選

  在首頁添加一個更新數據的按鍵

 

   頁面顯示

 

 

 

 

 

 

   六,刪除數據

  ①路由

 

   ②視圖

 

 

class SubjectDeleteView(View):
    def get(self, request):
        data = request.GET
        res = {'status': 0, 'msg': '刪除成功'}
        try:
            Subject.objects.get(id=data.get('id')).delete()
        except Exception as e:
            print(e)
            res = {'status': 1, 'msg': '刪除失敗'}
        return JsonResponse(res)

  這里直接刪除題目應該會同時清除選修班表和答案表,如果刪除是出現外鍵關聯錯誤導致無法刪除可以,修改代碼先刪除選修表和答案表以后再刪除題目表

 Options.objects.filter(subject_id=data.get('id')).delete()
 Answer.objects.filter(subject_id=data.get('id')).delete()
 Subject.objects.get(id=data.get('id')).delete()

  

  ③模板

  刪除數據沒有單獨的模板,在index頁面添加刪除函數

function subject_delete(id) {
            if (confirm('確認刪除嗎?')) {
            {#alert(id)#}
                $.get("{% url 'subject_delete' %}?id=" + id,function (data) {
                if(data.status == 0) {
                    swal({
                        title: data.msg,
                        icon: "success",
                        confirmButtonText: '確定',
                    }, function () {
                        window.location.reload()
                    });
                    } else {
                    swal("刪除失敗", {
                        icon: "error",
                    });
                }
            });
            }
        }

 

   在頁面增加刪除按鍵

 

 

 <a type = 'button' onclick="subject_delete({{ one.id }})">刪除</a>

  頁面顯示

 

 

 

 

 

   七,隨機生成一套試卷

  首先創建一套試卷表,和題目表類似

  設計表結構如下

 

   模板

 

 

# 試卷表開始
class Test_Paper_Subject(models.Model):
    stem = models.CharField(max_length=254, verbose_name='題干內容', blank=False, null=False, unique=True)
    type = models.IntegerField(choices=Type, verbose_name='題目類型,單選還是多選')
    explain = models.CharField(max_length=512, verbose_name='題目答案解析', blank=False, null=False)
    test_paper = models.ForeignKey('Test_Paper')

    class Meta:
        db_table = 'test_paper_subject'
        verbose_name = '題干表'

class Test_Paper_options(models.Model):
    options = models.IntegerField(choices=Option, verbose_name='選項ABCDEFGH')
    content = models.CharField(max_length=256, verbose_name='選項內容')
    subject = models.ForeignKey('Test_Paper_Subject')

    class Meta:
        db_table = 'test_paper_options'
        verbose_name = '選項表'
        unique_together = ('subject', 'content')
        ordering = ['options']

class Test_Paper_Answer(models.Model):
    options = models.IntegerField(choices=Option, verbose_name='選項ABCDEFGH')
    subject = models.ForeignKey('Test_Paper_Subject')

    class Meta:
        db_table = 'test_paper_answer'
        verbose_name = '答案表'
        unique_together = ('subject', 'options')
        ordering = ['options']

class Test_Paper(models.Model):
    class Meta:
        db_table = 'test_paper'

# 試卷表結束

  更新數據庫

python manage.py makemigrations subject
python manage.py migrate subject

  

 

   查看數據庫多出的幾張表

 

 

  在數據庫插入一定數據以后隨機生成一套試卷其中單選70道多選30道

  ①路由

 

 

 url(r'^test_paper_add', TestPaperAdd.as_view(), name=''),

  ②視圖

 

   

class TestPaperAdd(View):
    def get(self, request):
        subject_obj = Subject.objects.filter(type=0).order_by('?')[:70]
        subject_obj2 = Subject.objects.filter(type=1).order_by('?')[:30]
        # subject_obj = Subject.objects.all()
        Test_Paper.objects.all().delete()
        test_paper = Test_Paper()
        test_paper.save()
        test_paper_id = test_paper.id
        print(test_paper_id)

        for one in subject_obj:
            test_paper_subject = Test_Paper_Subject()
            test_paper_subject.stem = one.stem
            test_paper_subject.type = one.type
            test_paper_subject.explain = one.explain
            test_paper_subject.test_paper_id = test_paper_id
            test_paper_subject.save()

            for options in one.options_set.all():
                test_paper_options = Test_Paper_options()
                print(options.options)
                test_paper_options.options = options.options
                print(options.content)
                test_paper_options.content = options.content
                print(test_paper_subject.id)
                test_paper_options.subject_id = test_paper_subject.id
                test_paper_options.save()

            for answer in one.answer_set.all():
                test_paper_answer = Test_Paper_Answer()
                print(answer.options)
                test_paper_answer.options = answer.options
                test_paper_answer.subject_id = test_paper_subject.id
                test_paper_answer.save()

        for one in subject_obj2:
            test_paper_subject = Test_Paper_Subject()
            test_paper_subject.stem = one.stem
            test_paper_subject.type = one.type
            test_paper_subject.explain = one.explain
            test_paper_subject.test_paper_id = test_paper_id
            test_paper_subject.save()

            for options in one.options_set.all():
                test_paper_options = Test_Paper_options()
                print(options.options)
                test_paper_options.options = options.options
                print(options.content)
                test_paper_options.content = options.content
                print(test_paper_subject.id)
                test_paper_options.subject_id = test_paper_subject.id
                test_paper_options.save()

            for answer in one.answer_set.all():
                test_paper_answer = Test_Paper_Answer()
                print(answer.options)
                test_paper_answer.options = answer.options
                test_paper_answer.subject_id = test_paper_subject.id
                test_paper_answer.save()

        return HttpResponse('隨機生成一套試卷')

  代碼解析

 

   頁面生成一套試卷

 

   顯示試卷

  ①路由

 

 

 url(r'^test_paper_show', TestPaperShow.as_view(), name=''),

  ②視圖

 

 

class TestPaperShow(View):
    def get(self, request):
        data = Test_Paper.objects.all()
        # print(data, data.test_paper_subject_set.all())
        for one in data:
            data2 = one.test_paper_subject_set.all()
        return render(request, 'test_paper_show.html', {'object_list': data2})

  ③模板

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>試卷</title>
</head>
<body>
    {% for one in object_list  %}
        {% if one.type == 0 %}
            <p>單選</p>
        {% else %}
            <p>多選</p>
        {% endif %}
{#        顯示題干#}
        <p>{{ forloop.counter }} , {{ one.stem }}</p>

{#        顯示選項及內容#}
        <form id="{{ one.id }}">
         {% csrf_token %}
        {% for options in one.test_paper_options_set.all %}
            {% if one.type == 0 %}
                <input type="radio" name={{ one.id }} value="{{ options.options }}"> {{ options.get_options_display }} , {{ options.content }}
                {% else %}
                <input type="checkbox"  name={{ one.id }} value="{{ options.options }}">  {{ options.get_options_display }} , {{ options.content }}
            {% endif %}
            <br/>
        {% endfor %}
{#        <button class="btn btn-primary" type="submit">確定</button>#}
        <form/>
{#        顯示答案#}
        <p id="{{ one.id }}id" hidden>
        {% for answer in one.test_paper_answer_set.all %}
           {{ answer.get_options_display }}
        {% endfor %}
        </p>
        <input type = 'button' onclick=showp("{{ one.id }}id") value='答案'/>


{#        顯示解析#}
        <p id="{{ one.id }}explain" hidden >{{ one.explain }} </p>
        <input type = 'button' onclick=showp("{{ one.id }}explain") value='解析'>
        <a type = 'button' href="{% url 'subject_update' %}?id={{ one.id }}">修改</a>
{#        <a type = 'button' onclick="subject_delete({{ one.id }})">刪除</a>#}

    {% endfor %}
<script src="/static/js/jquery-3.1.1.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<script src="/static/js/plugins/metisMenu/jquery.metisMenu.js"></script>
<script src="/static/js/plugins/slimscroll/jquery.slimscroll.min.js"></script>
<script src="/static/js/plugins/validate/jquery.validate.js"></script>
<script src="/static/js/plugins/validate/messages_zh.js"></script>
<script src="/static/js/plugins/sweetalert/sweetalert.min.js"></script>
<!-- Custom and plugin javascript -->
<script src="/static/js/inspinia.js"></script>
<script src="/static/js/plugins/pace/pace.min.js"></script>
        <script type="text/javascript">
		function showp(id){
		        if (document.getElementById(id).style.display == 'inline') {
                    document.getElementById(id).style.display = 'none';
                }
                else {
                     document.getElementById(id).style.display='inline';
                }

		    }

		function subject_delete(id) {
            if (confirm('確認刪除嗎?')) {
            {#alert(id)#}
                $.get("{% url 'subject_delete' %}?id=" + id,function (data) {
                if(data.status == 0) {
                    swal({
                        title: data.msg,
                        icon: "success",
                        confirmButtonText: '確定',
                    }, function () {
                        window.location.reload()
                    });
                    } else {
                    swal("刪除失敗", {
                        icon: "error",
                    });
                }
            });
            }
        }

	    </script>
</body>
</html>

  web頁面查看

 

 

 

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM