使用models.FileField时如何获取上载文件的名称和URL

时间:2018-09-18 14:00:52

标签: django model upload

我正在使用以下文件:

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})

模板:climate / 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中,网址为空:

<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?

3 个答案:

答案 0 :(得分:2)

您正在尝试访问docfile对象(这是一个 document 模型实例)的Pic属性,但没有该属性< br />
因此,应该是

{{ document.photo.url }}
而不是
{{ document.docfile.url }}

答案 1 :(得分: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 :(得分:0)

执行以下操作:

{% 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 %}

因为您想显示图片信息