如何阻止django在sqlite3数据库中存储图像路径

时间:2016-05-26 10:18:17

标签: python django sqlite

以下代码可以很好地将缩略图图像存储在/ media /目录中。我想将所有图像存储在以下目录中,但django还将图像路径保存在数据库中。请告诉我,如何阻止django在数据库中保存路径和地址?

model.py:代码

from django.db import models
    class Document(models.Model):
        thumbnail = models.ImageField()

views.py:代码

from .models import Document
from .forms import DocumentForm

    if (request.FILES['thumbnail']):
        newdoc = Document(thumbnail = request.FILES['thumbnail'])
        newdoc.save()

forms.py:代码

from django import forms

    class DocumentForm(forms.Form):
        thumbnail = forms.ImageField(
        label='Select a file',
        help_text='max. 42 megabytes'
        )

template.html:代码

<form action="" method="post" id="imgUpload" enctype="multipart/form-data">
    <p>{{ form.non_field_errors }}</p>
    <p>{{ form.thumbnail.label_tag }} {{ form.thumbnail.help_text }}</p>
    <p>
        {{ form.thumbnail.errors }}
        {{ form.thumbnail }}
        <button type="submit" id="thumbUpload" class="btn btn-success"><i class="glyphicon glyphicon-picture"></i>&nbsp;&nbsp;Upload Thumbnails</button>
</form>

2 个答案:

答案 0 :(得分:1)

您必须覆盖表单方法,在保存有效表单之前,或者您可以处理代码,您不需要拥有可以处理的模型或表单

image = request.FILES['myfile']

现在您拥有的图像可以直接保存而无需模型

从Django文档转载的示例。

从django.http导入HttpResponseRedirect 来自django.shortcuts导入render_to_response

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', {'form': form})

def handle_uploaded_file(f):
    destination = open('file path', 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()

您可以更改文件路径&#39;使用您要存储图像的路径

答案 1 :(得分:0)

我不清楚你想要实现的目标,但解决方案很简单。只需获取文件对象并保存...

哦..还有一件事就是删除models.py和其他文件中的所有缩略图......

def handle_uploaded_file(f):
    destination = open('your_media_path/media/file.png', 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()
在POST视图中

f = request.FILES['thumbnail']
handle_uploaded_file(f)