Django循环所有现有记录进行保存,但仅保存一条记录

时间:2019-11-06 04:13:31

标签: django

这是我的HTML代码

<tr>
    <td colspan="2" style="text-align: center;">
        <h2 style="font-weight: bold;">Required Documents:</h2>
    </td>
</tr>
{% for d in doc %}
<tr>
    <td style="text-align: left;">
        <input type="file" name="myfile-{{d.id}}" value="{{d.id}}" style="outline: none;" required/>
        {{d.id}}{{d.Description}}
    </td>
    <td></td>
</tr> 
{% endfor %}

views.py

def enrollmentform(request):
    id = request.GET.get('StudentID')
    students = StudentProfile.objects.all().filter(id=id)
    doc = DocumentRequirement.objects.all().filter()
    return render(request, 'accounts/EnrollmentForm.html',
                  {"doc": doc})

这是我保存记录的逻辑

myfile = request.FILES['myfile-6']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
V_insert_data = StudentsEnrollmentRecord(
    Student_Users=studentname, Payment_Type=payment,
    Education_Levels=educationlevel, School_Year=schoolyear
)
insert_doc = StudentsSubmittedDocument(
    Students_Enrollment_Records =  V_insert_data,
    Document = myfile
)
insert_doc.save()

我不知道如何循环播放此 myfile = request.FILES ['myfile-6'] 使用表格文档的现有ID。请帮助我,我在3天的时间里遇到了这个问题

例如,如果学生遵守了4份必需的文件,它将像这样保存

correct

就我而言,它仅保存1条记录,

wrong saving

1 个答案:

答案 0 :(得分:0)

您可以有许多同名输入,可以重复输入

<input type="file" name="myfile">

您认为可以使用getlist

访问此已提交文件列表
files = request.FILES.getlist('myfile')

然后您遍历视图中的文件

V_insert_data = StudentsEnrollmentRecord(
    Student_Users=studentname,
    Payment_Type=payment,
    Education_Levels=educationlevel,
    School_Year=schoolyear
)
for file in request.FILES.getlist('myfile'):
    StudentsSubmittedDocument.objects.create(
        Students_Enrollment_Records=V_insert_data,
        Document=file
    )