我怎么知道哪个请求中的特定文件是从哪个输入标签上传的?

时间:2019-01-30 11:46:50

标签: python html django html-input

问题描述:

我有一个django视图和模板,其中显示了几段数据,这些数据是从模型中检索到的。每个图像下方都有一个<input type="file">标签,用于上传与每一行数据有关的图像。用户上载文件时,他可以为模型的某一特定行上载1到多个文件,或者可以选择不为一个或多个模型上载文件。我需要使用外键将这些文件保存到该特定行。我没有为此使用django表单。

再次解释一下,我的html中有几个文件标签,每个文件标签都来自模型不同行的一组特定文本下方。在POST时,所有文件都被收集到request.FILES内的列表中,不知道每个文件是从哪个输入标签上载的。我需要区分从不同文件标签上传的文件,因为这些文件需要保存到模型中,并通过外键引用不同的行。 如何知道请求中特定文件的输入标记?

我的模特:

class Procedure(models.Model):
    procid = models.AutoField(primary_key=True, unique=True)
    timestr = models.DateTimeField(default=timezone.now)
    template = models.ForeignKey(ProcedureTemplate, on_delete=models.CASCADE, blank=True, null=True)
    clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE)
    doctor = models.ForeignKey(doctor, on_delete=models.SET_NULL, blank=True, null=True)
    customer = models.ForeignKey(customer, on_delete=models.CASCADE, null=False)

    def __str__(self):
        return f'{self.template} for {self.customer} on {self.timestr}'

class SectionHeading(models.Model):
    procid = models.AutoField(primary_key=True, unique=True)
    name = models.CharField(max_length=200)

    fieldtype_choice = (
        ('heading1', 'Heading1'),
        ('heading2', 'Heading2'),
        )
    fieldtype = models.CharField(
        choices=fieldtype_choice, max_length=100, default='heading1')

    template = models.ForeignKey(ProcedureTemplate, on_delete=models.CASCADE, null=False)

    def __str__(self):
        return f'{self.name} [{self.procid}]'

class SectionText(models.Model):
    procid = models.AutoField(primary_key=True, unique=True)
    name = models.CharField(max_length=200)
    widgettype_choice = (
        ('textarea', 'Textarea'),
        ('text', 'Short Text'),
        )
    widgettype = models.CharField(
        choices=widgettype_choice, max_length=100, default='text')

    heading = models.ForeignKey(SectionHeading, on_delete=models.CASCADE, null=False)
    def __str__(self):
        return f'{self.name} [{self.procid}]'



class SectionImage(models.Model):
    procid = models.AutoField(primary_key=True, unique=True)
    pic = StdImageField(upload_to="data/media/%Y/%m/%d", blank=True, variations={
        'large': (600, 400),
        'thumbnail': (150, 140, True),
        'medium': (300, 200),
    })
    procedure = models.ForeignKey(Procedure, on_delete=models.CASCADE, null=False)

    def __str__(self):
        return self.pic.url

我的观点:

if request.method == 'POST':
    print(request.POST, "\n\n")        
    headinglist = request.POST.getlist('qn[]')
    valuelist = request.POST.getlist('ans[]')
    for h, v in zip(headinglist, valuelist):
        print(h, v)
    print(request.FILES)
    filelist = request.FILES.getlist('uploaded[]')
    for f in filelist:
        print(f)
        report_pic = SectionImage(pic = f, procedure=proc)
        report_pic.save()
        print(f'Saved picture to disk: {f}')
    msg = "Updated successfully"

我的html:

{% for qn, ans in headingparagraph %}
<div class="row mt-4">
    <div class="col-md-24">
        <div class="form-group">
            <label for="exampleFormControlTextarea1">{{ qn.name }}</label>
                <input type="hidden" id="custId" name="qn[]" value="{{ qn.procid }}">

            <textarea class="form-control reporttextarea" id=""  rows="3" name="ans[]">{{ ans }}</textarea>
        </div>
    </div>
</div>
<div class="row mb-2">
    <i class="fas fa-image fa-2x mx-2"></i> Upload Images <input type="file" class="mx-2" id="{{ qn.procid }}_upload" accept="image/*" name="uploaded[]" multiple />
</div>
{% endfor %}    

显示为:

<div class="row mt-4">
    <div class="col-md-24">
        <div class="form-group">
            <label for="exampleFormControlTextarea1">Nasal mucosa</label>
            <input type="hidden" id="custId" name="qn[]" value="1">
            <textarea class="form-control reporttextarea" id="" rows="3" name="ans[]">Normal nasal mucosa</textarea>
        </div>
    </div>
</div>
<div class="row mb-2">
    <i class="fas fa-image fa-2x mx-2"></i> Upload Images <input type="file" class="mx-2" id="1_upload" accept="image/*" name="uploaded[]" multiple />
</div>
<div class="row mt-4">
    <div class="col-md-24">
        <div class="form-group">
            <label for="exampleFormControlTextarea1">Turbinates</label>
            <input type="hidden" id="custId" name="qn[]" value="2">
            <textarea class="form-control reporttextarea" id="" rows="3" name="ans[]">Bilateral turbinates normal</textarea>
        </div>
    </div>
</div>
<div class="row mb-2">
    <i class="fas fa-image fa-2x mx-2"></i> Upload Images <input type="file" class="mx-2" id="2_upload" accept="image/*" name="uploaded[]" multiple />
</div>
<div class="row mt-4">
    <div class="col-md-24">
        <div class="form-group">
            <label for="exampleFormControlTextarea1">Middle meatus</label>
            <input type="hidden" id="custId" name="qn[]" value="3">
            <textarea class="form-control reporttextarea" id="" rows="3" name="ans[]">Bilateral middle meatus normal</textarea>
        </div>
    </div>
</div>
<div class="row mb-2">
    <i class="fas fa-image fa-2x mx-2"></i> Upload Images <input type="file" class="mx-2" id="3_upload" accept="image/*" name="uploaded[]" multiple />
</div>
<div class="row mt-4">
    <div class="col-md-24">
        <div class="form-group">
            <label for="exampleFormControlTextarea1">Inferior Meatus</label>
            <input type="hidden" id="custId" name="qn[]" value="4">
            <textarea class="form-control reporttextarea" id="" rows="3" name="ans[]">Inferior Meatus normal</textarea>
        </div>
    </div>
</div>
<div class="row mb-2">
    <i class="fas fa-image fa-2x mx-2"></i> Upload Images <input type="file" class="mx-2" id="4_upload" accept="image/*" name="uploaded[]" multiple />
</div>
<div class="row ">
    <div class="col-sm-12">
    </div>
    <div class="col-sm-2">
        <button type="submit" class="btn btn-primary btn-block">Save changes</button>
    </div>
    <div class="col-sm-12">
    </div>
</div>

当我上传Turbinates和Inferior Meatus的文件但不上传其他文件时,命令行上的输出是:

<QueryDict: {'csrfmiddlewaretoken': ['0dEBGstsSSzhOgebI2FBaHWioH7bEBmx0EPnYDE4nTrrNHZYMZCSTyId0FXAJYYR'], 'qn[]': ['1', '2', '3', '4'], 'ans[]': ['Normal nasal mucosa', 'Bilateral turbinates normal', 'Bilateral middle meatus normal', 'Inferior Meatus normal'], 'uploaded[]': ['', '']}> 
1 Normal nasal mucosa
2 Bilateral turbinates normal
3 Bilateral middle meatus normal
4 Inferior Meatus normal
<MultiValueDict: {'uploaded[]': [<InMemoryUploadedFile: Screenshot from 2019-01-27 11-32-34.png (image/png)>, <InMemoryUploadedFile: Screenshot from 2019-01-26 16-25-56.png (image/png)>, <InMemoryUploadedFile: Screenshot from 2019-01-26 16-25-18.png (image/png)>, <InMemoryUploadedFile: Screenshot from 2019-01-27 11-32-34.png (image/png)>]}>
Screenshot from 2019-01-27 11-32-34.png
Saved picture to disk: Screenshot from 2019-01-27 11-32-34.png
Screenshot from 2019-01-26 16-25-56.png
Saved picture to disk: Screenshot from 2019-01-26 16-25-56.png
Screenshot from 2019-01-26 16-25-18.png
Saved picture to disk: Screenshot from 2019-01-26 16-25-18.png
Screenshot from 2019-01-27 11-32-34.png
Saved picture to disk: Screenshot from 2019-01-27 11-32-34.png

所有文件都进入Querydict集合。我无法区分它属于哪个部分。有什么方法可以标记特定的文件标记,以便在提交表单时可以迭代列表并通过将每个文件标记到单独的节标题来保存每个文件。数据库部分很简单。我想知道如何构建文件标签/ html。

1 个答案:

答案 0 :(得分:1)

首先,不要使用[]来命名字段。那是PHP / Rubyism,在Django中不需要。

但是使用不同名称的方法是为输入提供这些名称。输入的name属性是FILES / POST词典中的键。