在Django中上传后如何获取文件绝对路径? [英] How do I get a files absolute path after being uploaded in Django?

查看:37
本文介绍了在Django中上传后如何获取文件绝对路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将文件上传到我的数据库,并在上传后导入它并最终将数据导出到我的数据库中.我的上传工作正常,但我不确定如何在上传后获取文件的绝对路径.我能够打印出文档的名称,但是如果上传了相同的文档名称,它会被附加但如果我调用 form.cleaned_data['document'].name.如何获取绝对文件路径,然后调用函数开始处理此文件?

I want to upload a file to my database and after it is uploaded import it and eventually export the data into my database. I have the uploading working just fine but I'm not sure how to get the absolute path of the file after it is uploaded. I'm able to print out the name of the document, but if the same document name is uploaded it is appended but still shows the original file name if I call form.cleaned_data['document'].name. What can I do to get the absolute file path and then call a function to start processing this file?

所以这就是我想要做的:

So this is what I'm looking to do:

  • 用户上传 .csv 文件
  • 文件保存在 db 中(带有描述和文件路径.文件路径正确存储在 db 中)
  • 获取刚刚上传的文件的位置
  • 开始处理此文件以转换 .csv 数据并存储在数据库中

models.py

from django.db import models

# Create your models here.
class Document(models.Model):
    description = models.CharField(max_length=255, blank=True)
    document = models.FileField(upload_to='documents/')
    uploaded_at = models.DateTimeField(auto_now_add=True)

views.py

from django.shortcuts import render, redirect
from django.views import View
# Create your views here.

from .forms import DocumentForm
from .models import Document   

class  FileUpload(View):
    def post(self, request):
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            print()
            print(form.cleaned_data['document'].name)
            form.save()
            return redirect('main_db_model:home')
        else:
            return render(request, 'file_upload_form.html', {
                'form': form
            })

    def get(self, request):
        form = DocumentForm()
        return render(request, 'file_upload_form.html', {
            'form': form
        })

forms.py

from django import forms
from .models import Document

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ('description', 'document', )

file_upload_form.html(模板):

file_upload_form.html (template):

{% extends "base.html" %}

{% block content %}
  <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Upload</button>
  </form>
      {% if saved %}
         <strong>Your profile was saved.</strong>
      {% endif %}
  This is the form page
  <p><a href="{% url 'main_db_model:home' %}">Return to home</a></p>

    <p>Uploaded files:</p>
      <ul>
        {% for obj in documents %}
          <li>
            <a href="{{ obj.document.url }}">{{ obj.document.name }}</a>
            <small>(Uploaded at: {{ obj.uploaded_at }})</small>
            {{ obj.document.url }}
          </li>
        {% endfor %}
      </ul>
{% endblock %}

推荐答案

之前,我建议您将这个 upload_to='documents/' 更改为 upload_to='documents/%Y/%m/%d',为什么?这是为了处理 documents/ 路径中的巨大文档文件.

Previously, I suggest you to change this upload_to='documents/' to upload_to='documents/%Y/%m/%d', why? this to handle huge document files inside your path of documents/.

form.cleaned_data['document'](或 request.FILES['document'])返回一个 UploadedFile 对象.当然 form.cleaned_data['document'].name 应该只返回一个名字.

form.cleaned_data['document'] (or request.FILES['document']) return a UploadedFile object. of course form.cleaned_data['document'].name should return a name only.

class  FileUpload(View):
    def post(self, request):
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            # this `initial_obj` if you need to update before it uploaded.
            # such as `initial_obj.user = request.user` if you has fk to `User`, 
            # if not you can only using `obj = form.save()`
            initial_obj = form.save(commit=False)
            initial_obj.save()

            # return path name from `upload_to='documents/'` in your `models.py` + absolute path of file.
            # eg; `documents/filename.csv`
            print(initial_obj.document)

            # return `MEDIA_URL` + `upload_to` + absolute path of file.
            # eg; `/media/documents/filename.csv`
            print(initial_obj.document.url)

            form.save()

但是如果你使用 upload_to='documents/%Y/%m/%d',你会得到不同的结果,

But you will get a different if you using upload_to='documents/%Y/%m/%d',

print(initial_obj.document)      # `documents/2017/02/29/filename.csv`

print(initial_obj.document.url)  # `/media/documents/2017/02/29/filename.csv`

这篇关于在Django中上传后如何获取文件绝对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆