首页 > 解决方案 > Django显示多个上传的文件

问题描述

我正在尝试显示多个上传的文件 URL,但我不知道该怎么做。我是一个表单,用户可以使用它来上传多个运行良好的文件,但现在我希望能够显示这些文件。例如,一家公司可以拥有多个文件。

class InternationalCompany(models.Model):
    International_company_Name = models.CharField(max_length=50)
    International_company_Id = models.CharField(max_length=50)
    options = (
        ('Yes', 'Yes'),
        ('No', 'No'),
    )
    Does_it_have_a_Financial_Dealers_License = models.CharField(max_length=20, choices=options, null=True) 
    Register_Office = models.TextField(max_length=500, null=True)
    Beneficial_owner = models.CharField(max_length=100, null=True)
    Beneficial_owner_id = models.FileField(upload_to='passport/pdf/',null=True)
    expire_date = models.DateField(null=True)
    BO_Phone_number = models.IntegerField(null=True)
    BO_Email_Address = models.EmailField(null=True)
    BO_Residential_Address = models.TextField(max_length=200, null=True)
    
    def __str__(self):
        return self.International_company_Name


class SupportDocuments(models.Model):
    Supporting_Documents = models.FileField(upload_to='support_doc/pdf/', null=True)
    internationalcompany = models.ForeignKey(InternationalCompany, on_delete=models.CASCADE)
    def __str__(self):
        return self.Supporting_Documents.url

我尝试了类似的方法,但它只显示了文件的一个 url,而不是与该公司关联的文件的多个 url。

{%for company in doc%}
     <tr>
        <td></td>

        <td>{{company.internationalcompany.Beneficial_owner}}</td>
          <td>{{company.Supporting_Documents.url}}</td>

     </tr>

{%endfor%}

我也试过这个,但它没有显示任何东西。

  {%for company in doc.Supporting_Documents.all%}

    {{company.url}}

    
{%endfor%}

def supporting_doc(request, company_id):
    doc = SupportDocuments.objects.filter(id=company_id)
    return render(request, 'supporting_doc.html', locals())

标签: djangodjango-templates

解决方案


首先,使用它可能contextlocals() 这里讨论的更好

其次,您获取文档查询集的方式是错误的。id=company_id的 id 与SupportingDocuments不同company_id。你真正需要做的是internationalcompany.id=company_id

所以views.py:

def supporting_doc(request, company_id):
    documents = SupportDocuments.objects.filter(internationalcompany.id=company_id)
    context = { "documents": documents}

    return render(request, 'supporting_doc.html', context)

在模板中:

{% for doc in documents %}
{{ doc.internationalcompany.Beneficial_owner}}
{{ doc.Supporting_Documents }}
{% endfor %}

附带说明一下,在字段中使用所有小写字母可能会更好。这样,很容易区分字段和模型。


推荐阅读