问题描述
我正在尝试使用Django表单上传文件,并将这些文件保存在数据库本身中.我已经能够将文件的链接保存在数据库中,并将文件本身保存在我在Media_root中指定的目录中.
I am trying to upload files using django forms and save those files in the database itself.I have been able to save the link of the file in database and save the file itself in a directory which i specified in Media_root.Can you please help me and tell me what can i change in my code so that files are saved in the database.
这是我的代码:
from django.db import models
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
forms.py
Django导入表单中的forms.py
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
)
views.py
来自django.shortcuts的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')
app \ urls.py
django.conf.urls中的app\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)
project \ urls.py
django.conf.urls中的project\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'),)
推荐答案
Django提供了 BinaryField ,可让您存储任何二进制数据,包括文件内容.
Django provides BinaryField that lets you store any binary data, including file contents.
请注意,文档还显示:
如果您不想将文件存储在Web服务器的文件系统上,则可以探索其他选项,例如Amazon S3或仅FTP服务器.看一下 django-storages 库,它提供了很多不错的选择.
If you'd rather not store the files on your web server's file system, you can explore other options such as Amazon S3 or just an FTP server. Have a look at the django-storages library, it provides a nice bunch of options.
这篇关于如何在Django中将文件保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!