今天的Django教训汇总:建立题库-20210416

本文介绍了如何在Django框架下创建一个试题管理系统,包括新增题库(通过Excel文件批量导入)、查询题库(根据Subject_id和category筛选)、下载题库及修改题库的功能。主要涉及Model、Form、View和Template的使用,以及数据库操作和文件上传。
摘要由CSDN通过智能技术生成

本文说明如何在训练系统中新增题库、查询题库、下载题库、修改题库。

1.新增题库

建立题库的思路如下:

在model.py建立TestPaper,并在admin.py登记TestPaper,然后在form.py中对应建立UploadTestPaperForm,然后在views.py编写upload_test_paper,并在template中上传的form。
#models.py

# 试题类TestPaper
class TestPaper(models.Model):
    subject = models.ForeignKey(Subject,on_delete=models.CASCADE)
    category = models.CharField(max_length=100)
    title = models.CharField(max_length = 300,null=True)
    Option_CHOICES = (
        (u'A', u'A'),
        (u'B', u'B'),
        (u'C', u'C'),
        (u'D', u'D'),
    )
    item_1 = models.CharField(max_length=100,choices=Option_CHOICES)
    answer = models.CharField(max_length=100,choices=Option_CHOICES)

    def __str__(self):
        return '{0}-{1}'.format(self.subject.Subject_id,self.title)

#admin.py

admin.site.register(TestPaper)

#form.py

#UploadTestPaperForm
class UploadTestPaperForm(forms.Form):
    uploadfile = forms.FileField(label=r'请选择上传档案')
    name = forms.CharField(max_length=50,label=r'请填写本次的名字')

#views.py

# 批量上传testpaper
def upload_test_paper(request):
    if request.method == "POST":  #验证POST
        uf = UploadTestPaperForm(request.POST,request.FILES) #.post是获取post返回字段,.FILES是获取返回的文件
        #print(uf)
        #print(request.FILES['uploadfile'])
        #print('-----------')
        if uf.is_valid(): #判断前台返回的表单是否为有效的类型
            wb = load_workbook(filename=request.FILES['uploadfile'])
            print(wb)
            ws = wb.get_sheet_names()
            ws = wb.get_sheet_by_name(ws[0])
            max_row = ws.max_row
            for row in range(2,max_row+1):
                #获取表单元素
                subject = ws.cell(row=row,column=1).value
                category = ws.cell(row=row,column=2).value
                title = ws.cell(row=row,column=3).value
                item_1 = ws.cell(row=row,column=4).value
                answer = ws.cell(row=row,column=5).value
                #实例化subject和employee
                subject_instant = Subject.objects.filter(Subject_id=subject)[0]
                # 写入数据库
                my_upload_file = TestPaper()
                my_upload_file.subject = subject_instant
                my_upload_file.category = category
                my_upload_file.title = title
                my_upload_file.item_1 = item_1
                my_upload_file.answer = answer
                my_upload_file.save()
            return HttpResponse('upload ok!')
    else:
        uf = UploadTestPaperForm()
    return render(request,'myclass/upload_test_paper.html',{'uf':uf})

#upload_test_paper.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>upload_employee</title>
</head>

<body>
    <form enctype="multipart/form-data" action="" method="POST">
        {% csrf_token %}
        {{uf.as_p}}
        <input type="submit" value="upload"/>
     </form>

</body>
</html>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.查询题库

建立题库的思路如下:

在model.py建立TestPaper并上传试题后,然后在form.py中对应建立QueryTestPaperForm,然后在views.py编写query_test_paper,并在template中同时放入查询条件和查询结果。

#forms.py

#查询题库的条件Form
class QueryTestPaperForm(forms.Form):
    Subject_id = forms.ModelChoiceField(label=r'请输入Subject_id',required=False,queryset=Subject.objects.all())
    category_CHOICES = (
        (u'1', u'1'),
        (u'2', u'2'),
    )
    category = forms.ChoiceField(label=r'请输入category',choices= category_CHOICES,required=False,widget=forms.widgets.RadioSelect())

#views.py

def query_test_paper(request):
    test_paper_list=[]
    print(request.method)
    if request.method == 'POST' and request.POST:
        form = QueryTestPaperForm(data=request.POST)
        if form.is_valid():
            Subject_id = form.cleaned_data['Subject_id']
            category = form.cleaned_data['category']
            # 表中添加数据
            if Subject_id is None:
                test_paper_list = TestPaper.objects.all()
            elif Subject_id and category:
                #请注意下方的filter(subject_id=Subject_id)的subject_id是小写
                test_paper_list = TestPaper.objects.filter(subject_id=Subject_id).filter(category__contains=category)
            elif Subject_id:
                #请注意下方的filter(subject_id=Subject_id)的subject_id是小写
                test_paper_list = TestPaper.objects.filter(subject_id=Subject_id)
            elif category:
                test_paper_list = TestPaper.objects.filter(category__contains=category)
        else:
            form = QueryTestPaperForm()
    else:
        form = QueryTestPaperForm()
    context={'test_paper_list': test_paper_list,'form':form}
    return render(request, 'myclass/search_test_paper_all.html',context=context)

#search_test_paper_all.html

<html>
<head>
    <title>search_form</title>
</head>

<body>
    <h1>search_form</h1>
    <form action="/myclass/query_test_paper/" method="POST">
        <a>可以输入其他信息</a>

        <br>
        {{form.as_p}}
        {% csrf_token %}
        <input type="submit" value="Search">
    </form>

    {% if test_paper_list %}
    <h1>search_result</h1>
    <table>
        <p>题库</p>
        <tr align="center" style="color:White;background-color:#3366FF;font-family:微軟正黑體,Tahoma,Arial,微軟雅黑體;font-size:14px;">
            <th scope="col">subject</th>
            <th scope="col">category</th>
            <th scope="col">title</th>
            <th scope="col">item_1</th>
            <th scope="col">answer</th>
        </tr>


        {% for test_paper in test_paper_list %}
        <tr align="center" valign="middle" style="color:Black;background-color:#EFF3FB;border-color:#E0E0E0;border-width:1px;border-style:solid;height:26px;">
            <td>{{ test_paper.subject.Subject_id }}</td>
            <td>{{ test_paper.category }}</td>
            <td>{{ test_paper.title }}</td>
            <td>{{ test_paper.item_1 }}</td>
            <td>{{ test_paper.answer }}</td>
        </tr>
        {% endfor %}
    </table>
    {% endif %}

</body>

在这里插入图片描述

错误1:Cannot resolve keyword ‘Subject_id’ into field. Choices are: answer, category, id, item_1, subject, subject_id, title

#views.py

def query_test_paper(request):
    test_paper_list=[]
    print('---------------')
    print(request.method)
    print('---------------')
    if request.method == 'POST' and request.POST:
        form = QueryTestPaperForm(data=request.POST)
        if form.is_valid():
            Subject_id = form.cleaned_data['Subject_id']
            category = form.cleaned_data['category']
            # 表中添加数据
            if Subject_id and category:
                test_paper_list = TestPaper.objects.filter(Subject_id=Subject_id).filter(category__contains=category)
                return render(request,'myclass/search_test_paper_all.html',context={'test_paper_list': test_paper_list,'form':form})

        else:
            form = QueryTestPaperForm()
    else:
        form = QueryTestPaperForm()
    context={'test_paper_list': test_paper_list,'form':form}
    return render(request, 'myclass/search_form_for_paper.html',context=context)

在这里插入图片描述

解法:Subject_id改成subject_id
#views.py

def query_test_paper(request):
    test_paper_list=[]
    print('---------------')
    print(request.method)
    print('---------------')
    if request.method == 'POST' and request.POST:
        form = QueryTestPaperForm(data=request.POST)
        if form.is_valid():
            Subject_id = form.cleaned_data['Subject_id']
            category = form.cleaned_data['category']
            # 表中添加数据
            if Subject_id and category:
            #请注意下方的filter(subject_id=Subject_id)的subject_id是小写
                test_paper_list = TestPaper.objects.filter(Subject_id=Subject_id).filter(category__contains=category)
                return render(request,'myclass/search_test_paper_all.html',context={'test_paper_list': test_paper_list,'form':form})

        else:
            form = QueryTestPaperForm()
    else:
        form = QueryTestPaperForm()
    context={'test_paper_list': test_paper_list,'form':form}
    return render(request, 'myclass/search_form_for_paper.html',context=context)

在这里插入图片描述

3.下载题库

4.修改题库

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值