Django没有将照片保存到文件夹但是将图像路径保存到表格

时间:2014-11-13 10:53:43

标签: python html django django-forms django-views

我想将照片保存到文件夹但不起作用。虽然表单(路径和照片名称)已保存在数据库中,但照片未保存到文件夹中。

settings.py

import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS, MEDIA_ROOT = [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'mediafiles')]
MEDIA_URL = '/photos/'

文件结构

mySite/
    myApp/
        mediafiles/
            photos
        templates
        __init__.py
        admin.py
        models.py
        forms.py
        urls.py
        views.py

models.py

class NewImage(models.Model):
    thumbnail = models.ImageField(upload_to='photos/')
    time_created = models.DateTimeField()

forms.py

class ImageForm(forms.ModelForm):
class Meta:
    model = NewImage

urls.py

 url(r'^newimage/$', views.newImage, name='image'),

views.py

def newImage(request):
    if request.method == 'POST':
        imageForm = ImageForm(request.POST, request.FILES or None)
        if imageForm.is_valid():
            date = imageForm.cleaned_data['time_created']
            img = imageForm.cleaned_data['thumbnail']
            imageForm.save()
            return HttpResponse('Upload successful on '+ date)
        else:
            context = {'imageForm': imageForm}
            return render(request, 'mysite/imageForm.html', context)
    else:
        imageForm = ImageForm()
        context = {'imageForm': imageForm}
        return render(request, 'mysite/imageForm.html', context)

HTML

<form method="post" class="form-horizontal" name="form1" enctype="multipart/form-data" action=".">
{% csrf_token %}
    <h2>Upload a picture: </h2>
    <div class="control-group">
        <div class="controls">
            {{ imageForm.as_p }}    
        </div>
    </div>
    <br/>  
    <div align="center">
        <button class="btn" name = "upload" type="submit">Upload...</button>
    </div> 
</form>

0 个答案:

没有答案