【问题标题】:How to get the name and url of an uploaded file when using models.FileField使用models.FileField时如何获取上传文件的名称和url
【发布时间】:2019-02-22 14:15:52
【问题描述】:

我正在使用以下文件:

settings.py:

MEDIA_URL = '/data/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'data')

urls.py:

urlpatterns = [
    path("photo/upload", views.upload_pic, name="uploadpic ")
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

models.py:

class Pic(models.Model):
    name = models.CharField(max_length=255)
    photo = models.FileField(upload_to="data/media/%Y/%m/%d")
    def __str__(self):
        return self.url
    def path(self):
        return self.url

forms.py:

from django import forms
class DocumentForm(forms.Form):
    docfile = forms.FileField(
        label='Select a file',
        help_text='any valid file'
    )

views.py:

def upload_pic(request):
    documents = Pic.objects.all()
    import uuid
    name = uuid.uuid4().hex[:6].upper()
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            print(request.FILES)
            newdoc = Pic(name=name, photo=request.FILES['docfile'])
            newdoc.save()
            return render(request, 'clinic/list.html', {'documents': documents, 'form': form, 'msg': 'success'})
    else:
        form = DocumentForm()  # A empty, unbound form
    return render(request, 'clinic/list.html', {'documents': documents, 'form': form})

模板:clinic/list.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Minimal Django File Upload Example</title>
</head>
<body>
    <!-- List of uploaded documents -->
    {% if documents %}
    <ul>
        {% for document in documents %}
        <li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li>
        {% endfor %}
    </ul>
    {% else %}
    <p>No documents.</p>
    {% endif %}
    <!-- Upload form. Note enctype attribute! -->
    <form action="/clinic/photo/upload" method="post" enctype="multipart/form-data">        
        {% csrf_token %}
        <p>{{ form.non_field_errors }}</p>
        <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
        <p>
            {{ form.docfile.errors }}
            {{ form.docfile }}
        </p>
        <p><input type="submit" value="Upload" /></p>
    </form>
</body>
</html>

但是在呈现的 html 中,url 是空白的:

<body cz-shortcut-listen="true">
    <!-- List of uploaded documents -->        
    <ul>            
        <li><a href=""></a></li>            
        <li><a href=""></a></li>            
        <li><a href=""></a></li>            
        <li><a href=""></a></li>            
        <li><a href=""></a></li>            
        <li><a href=""></a></li>            
        <li><a href=""></a></li>            
        <li><a href=""></a></li>            
        <li><a href=""></a></li>            
        <li><a href=""></a></li>            
        <li><a href=""></a></li>            
        <li><a href=""></a></li>            
        <li><a href=""></a></li>            
        <li><a href=""></a></li>            
    </ul>    
    <!-- Upload form. Note enctype attribute! -->
    <form action="/clinic/photo/upload" method="post" enctype="multipart/form-data">            
        <input type="hidden" name="csrfmiddlewaretoken" value="EYTXeSgaP00jHNFhyPvgomYVyHB8FpTEXm5T4WrXCPyjpqkSrO3bEtiGQqV5iqeL">
        <p></p>
        <p><label for="id_docfile">Select a file:</label> max. 42 megabytes</p>
        <p>                
            <input type="file" name="docfile" required="" id="id_docfile">
        </p>
        <p><input type="submit" value="Upload"></p>
    </form>
<iframe frameborder="0" scrolling="no" style="background-color: transparent; border: 0px; display: none;"></iframe><div id="GOOGLE_INPUT_CHEXT_FLAG" input="" input_stat="{&quot;tlang&quot;:true,&quot;tsbc&quot;:true,&quot;pun&quot;:true,&quot;mk&quot;:true,&quot;ss&quot;:true}" style="display: none;"></div></body>

How can I get the media name and url in the rendered template?

【问题讨论】:

    标签: django model upload


    【解决方案1】:

    问题是 docfile 不在您的模型中,您应该改用 document.photo。

    <!-- List of uploaded documents -->
    {% if documents %}
     <ul>
      {% for document in documents %}
      <li><a href="{{ document.photo.url }}">{{ document.photo.name }}</a></li>
      {% endfor %}
     </ul>
    {% else %}
      <p>No documents.</p>
    {% endif %}
    

    【讨论】:

      【解决方案2】:

      您正在尝试访问 document 对象的 docfile 属性(这是一个 Pic 模型实例)并且它没有该 arrtribute

      所以,应该是

      {{ document.<b>photo</b>.url }}
      而不是
      {{ document.docfile.url }}

      【讨论】:

        【解决方案3】:

        这样做:

        {% if documents %}
         <ul>
          {% for document in documents %}
          <li><a href="{{ document.photo.url }}">{{ document.photo.name }}</a></li>
          {% endfor %}
         </ul>
        {% else %}
          <p>No documents.</p>
        {% endif %}
        

        因为你想显示图片信息

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-04-22
          • 1970-01-01
          • 2015-01-28
          • 2016-08-15
          • 2017-06-10
          • 1970-01-01
          • 2021-01-10
          • 1970-01-01
          相关资源
          最近更新 更多