如何在django中将文件保存到数据库

时间:2016-07-28 06:37:40

标签: python django

我正在尝试使用django表单上传文件,并将这些文件保存在数据库本身中。 我已经能够将文件的链接保存在数据库中并将文件本身保存在我在Media_root中指定的目录中。您可以帮助我并告诉我我的代码中可以更改哪些文件保存在数据库中

这是我的代码:

models.py

from django.db import models


class Document(models.Model):
    docfile = models.FileField(upload_to='documents/%Y/%m/%d')

forms.py

from django import forms

class DocumentForm(forms.Form):
    docfile = forms.FileField(
        label='Select a file',
    )

views.py

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from .models import Document
from .forms import DocumentForm

def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('upload.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
    'list.html',
    {'documents': documents, 'form': form},
    context_instance=RequestContext(request)
    )

def index(request):
    return render_to_response('index.html')

应用\ urls.py

from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import RedirectView
from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
        (r'^upload/', include('upload.urls')),
        (r'^$', 'upload.views.index'),
        (r'^admin/', include(admin.site.urls)),) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

项目\ urls.py

from django.conf.urls import patterns, include, url

urlpatterns = patterns('upload.views',
    url(r'^$', 'list', name='list'),
    url(r'^list/$', 'list', name='list'),)

1 个答案:

答案 0 :(得分:5)

Django提供BinaryField,可以存储任何二进制数据,包括文件内容。

请注意文档也说:

  

虽然您可能会考虑将文件存储在数据库中,但请考虑在99%的情况下这是不好的设计。此字段不能替代正确的静态文件处理。

如果您不想将文件存储在网络服务器的文件系统中,您可以探索其他选项,例如Amazon S3或只是FTP服务器。看看django-storages库,它提供了很多选项。