作为Django的新手,我在Django 1.3中制作上传应用程序时遇到了困难。我找不到任何最新的示例/代码段。可能有人发布了一个最小但完整的(模型,视图,模板)示例代码吗?
答案 0 :(得分:65)
一般来说,当你试图“只是得到一个有效的例子”时,最好“开始编写代码”。这里没有任何代码可以帮助您,因此它可以让我们更多地回答这个问题。
如果你想获取一个文件,你需要在某个地方的html文件中使用这样的东西:
<form method="post" enctype="multipart/form-data">
<input type="file" name="myfile" />
<input type="submit" name="submit" value="Upload" />
</form>
这将为您提供浏览按钮,启动操作的上传按钮(提交表单)并记下enctype以便Django知道给您request.FILES
在视图某处,您可以使用
访问该文件def myview(request):
request.FILES['myfile'] # this is my file
中有大量信息
我建议您彻底阅读该页面并开始编写代码 - 然后在不起作用的情况下返回示例和堆栈跟踪。
答案 1 :(得分:62)
Akseli Palén's answer的更新。请参阅github repo,使用Django 2
运行startproject ::
$ django-admin.py startproject sample
现在创建了一个文件夹(示例)::
sample/
manage.py
sample/
__init__.py
settings.py
urls.py
wsgi.py
创建一个app ::
$ cd sample
$ python manage.py startapp uploader
现在创建了一个包含这些文件的文件夹(uploader
)::
uploader/
__init__.py
admin.py
app.py
models.py
tests.py
views.py
migrations/
__init__.py
在sample/settings.py
上将'uploader.apps.UploaderConfig'
添加到INSTALLED_APPS
并添加MEDIA_ROOT
和MEDIA_URL
,即::
INSTALLED_APPS = [
...<other apps>...
'uploader.apps.UploaderConfig',
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
sample/urls.py
添加:: 中的
...<other imports>...
from django.conf import settings
from django.conf.urls.static import static
from uploader import views as uploader_views
urlpatterns = [
...<other url patterns>...
path('', uploader_views.home, name='imageupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
更新uploader/models.py
::
from django.db import models
from django.forms import ModelForm
class Upload(models.Model):
pic = models.FileField(upload_to="images/")
upload_date=models.DateTimeField(auto_now_add =True)
# FileUpload form class.
class UploadForm(ModelForm):
class Meta:
model = Upload
fields = ('pic',)
更新uploader/views.py
::
from django.shortcuts import render
from uploader.models import UploadForm,Upload
from django.http import HttpResponseRedirect
from django.urls import reverse
# Create your views here.
def home(request):
if request.method=="POST":
img = UploadForm(request.POST, request.FILES)
if img.is_valid():
img.save()
return HttpResponseRedirect(reverse('imageupload'))
else:
img=UploadForm()
images=Upload.objects.all().order_by('-upload_date')
return render(request,'home.html',{'form':img,'images':images})
在文件夹上传器中创建文件夹模板,然后创建文件 home.html ,即sample/uploader/templates/home.html
::
<div style="padding:40px;margin:40px;border:1px solid #ccc">
<h1>picture</h1>
<form action="#" method="post" enctype="multipart/form-data">
{% csrf_token %} {{form}}
<input type="submit" value="Upload" />
</form>
{% for img in images %}
{{forloop.counter}}.<a href="{{ img.pic.url }}">{{ img.pic.name }}</a>
({{img.upload_date}})<hr />
{% endfor %}
</div>
Syncronize数据库和runserver ::
$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py runserver
答案 2 :(得分:27)
我必须说我发现django的文档令人困惑。 另外,对于最简单的例子,为什么要提到表格? 我在views.py中工作的例子是: -
for key, file in request.FILES.items():
path = file.name
dest = open(path, 'w')
if file.multiple_chunks:
for c in file.chunks():
dest.write(c)
else:
dest.write(file.read())
dest.close()
html文件看起来像下面的代码,虽然这个例子只上传了一个文件,保存文件的代码处理了很多: -
<form action="/upload_file/" method="post" enctype="multipart/form-data">{% csrf_token %}
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
这些例子不是我的代码,它们来自我发现的另外两个例子。 我是django的初学者,所以我很可能错过了一些关键点。
答案 3 :(得分:16)
在Henry's example上展开:
import tempfile
import shutil
FILE_UPLOAD_DIR = '/home/imran/uploads'
def handle_uploaded_file(source):
fd, filepath = tempfile.mkstemp(prefix=source.name, dir=FILE_UPLOAD_DIR)
with open(filepath, 'wb') as dest:
shutil.copyfileobj(source, dest)
return filepath
您可以使用上传的文件对象在视图中调用此handle_uploaded_file
函数。这将在文件系统中使用唯一名称(带有原始上载文件的文件名)保存文件,并返回已保存文件的完整路径。您可以将路径保存在数据库中,稍后对该文件执行某些操作。
答案 4 :(得分:15)
我也有类似的要求。网上的大多数例子都要求创建模型并创建我不想使用的表单。这是我的最终代码。
if request.method == 'POST':
file1 = request.FILES['file']
contentOfFile = file1.read()
if file1:
return render(request, 'blogapp/Statistics.html', {'file': file1, 'contentOfFile': contentOfFile})
在HTML中上传我写道:
{% block content %}
<h1>File content</h1>
<form action="{% url 'blogapp:uploadComplete'%}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="uploadbutton" type="file" value="Browse" name="file" accept="text/csv" />
<input type="submit" value="Upload" />
</form>
{% endblock %}
以下是显示文件内容的HTML:
{% block content %}
<h3>File uploaded successfully</h3>
{{file.name}}
</br>content = {{contentOfFile}}
{% endblock %}
答案 5 :(得分:11)
这可能对您有所帮助: 在models.py中创建一个文件字段
上传文件(在您的admin.py中):
def save_model(self, request, obj, form, change):
url = "http://img.youtube.com/vi/%s/hqdefault.jpg" %(obj.video)
url = str(url)
if url:
temp_img = NamedTemporaryFile(delete=True)
temp_img.write(urllib2.urlopen(url).read())
temp_img.flush()
filename_img = urlparse(url).path.split('/')[-1]
obj.image.save(filename_img,File(temp_img)
并在模板中使用该字段。
答案 6 :(得分:10)
您可以参考具有django版本的Fine Uploader中的服务器示例。 https://github.com/FineUploader/server-examples/tree/master/python/django-fine-uploader
它非常优雅,最重要的是,它提供了特色的js lib。模板不包含在服务器示例中,但您可以在其网站上找到演示。 精细上传者:http://fineuploader.com/demos.html
<强> views.py 强>
UploadView将发布和删除请求分派给各个处理程序。
class UploadView(View):
@csrf_exempt
def dispatch(self, *args, **kwargs):
return super(UploadView, self).dispatch(*args, **kwargs)
def post(self, request, *args, **kwargs):
"""A POST request. Validate the form and then handle the upload
based ont the POSTed data. Does not handle extra parameters yet.
"""
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_upload(request.FILES['qqfile'], form.cleaned_data)
return make_response(content=json.dumps({ 'success': True }))
else:
return make_response(status=400,
content=json.dumps({
'success': False,
'error': '%s' % repr(form.errors)
}))
def delete(self, request, *args, **kwargs):
"""A DELETE request. If found, deletes a file with the corresponding
UUID from the server's filesystem.
"""
qquuid = kwargs.get('qquuid', '')
if qquuid:
try:
handle_deleted_file(qquuid)
return make_response(content=json.dumps({ 'success': True }))
except Exception, e:
return make_response(status=400,
content=json.dumps({
'success': False,
'error': '%s' % repr(e)
}))
return make_response(status=404,
content=json.dumps({
'success': False,
'error': 'File not present'
}))
<强> forms.py 强>
class UploadFileForm(forms.Form):
""" This form represents a basic request from Fine Uploader.
The required fields will **always** be sent, the other fields are optional
based on your setup.
Edit this if you want to add custom parameters in the body of the POST
request.
"""
qqfile = forms.FileField()
qquuid = forms.CharField()
qqfilename = forms.CharField()
qqpartindex = forms.IntegerField(required=False)
qqchunksize = forms.IntegerField(required=False)
qqpartbyteoffset = forms.IntegerField(required=False)
qqtotalfilesize = forms.IntegerField(required=False)
qqtotalparts = forms.IntegerField(required=False)
答案 7 :(得分:6)
不确定这种方法是否有任何缺点,但在views.py:
中甚至更小entry = form.save()
# save uploaded file
if request.FILES['myfile']:
entry.myfile.save(request.FILES['myfile']._name, request.FILES['myfile'], True)
答案 8 :(得分:0)
我遇到了类似的问题,并由django管理站点解决。
# models
class Document(models.Model):
docfile = models.FileField(upload_to='documents/Temp/%Y/%m/%d')
def doc_name(self):
return self.docfile.name.split('/')[-1] # only the name, not full path
# admin
from myapp.models import Document
class DocumentAdmin(admin.ModelAdmin):
list_display = ('doc_name',)
admin.site.register(Document, DocumentAdmin)