2016-05-26 19 views
0

次のコードは/ media /ディレクトリにサムネイル画像を保存するために問題なく動作します。私は次のディレクトリにすべての画像を保存したいが、djangoは画像のパスをデータベースに保存する。私に教えてください、私はどのようにdjangoのパスとアドレスをデータベースに保存するのを止めることができますか?djangoを停止してsqlite3データベースに画像パスを保存する方法

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> 

答えて

0

私はあなたが達成しようとしているかについては明らかではないんだけど解決策はほとんど簡単です。ちょうどあなたのPOSTビューで...

ああ...もう一つは、ちょうど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() 

をファイルオブジェクトを取得し、保存

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

あなたvalidformを保存する前に、フォームのメソッドをオーバーライドする必要がある、またはあなたのコードで処理することができ、あなたはモデルを持っているか、あなたは

image = request.FILES['myfile'] 
で処理することができます形成する必要はありません。

今すぐモデルなしで直接保存できる画像があります

例をDjango Documentationから再現しました。 django.shortcutsからdjango.httpインポートHttpResponseRedirect から

は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() 

をインポートし、あなたのイメージ

を保存する場所、あなたのパスを持つ「ファイルパス」を変更することができます
関連する問題