简体   繁体   中英

Image upload not saving file in Django

No errors when hitting upload. But the image doesn't appear where I have indicated it ought to. Put an absolute path in MEDIA_ROOT and referenced the same in (upload_to) param ImageField. Not sure what I am missing.

Model:

class FileUploadHandler(models.Model):
    title = models.CharField(max_length=100)
    file = models.ImageField(upload_to='/Python27/Lib/site-packages/django/bin/mideastinfo/wiki/static/')

View:

from models import Article, Edit
from forms import ArticleForm, EditForm
from forms import *
from PIL import Image
from models import FileUploadHandler

def image_upload(request):
    if request.method == 'POST':
        form = UploadImageForm(request.POST, request.FILES)
        if form.is_valid():
            FileUploadHandler(request.FILES['image'])
            return render_to_response('wiki/gallery.html')
    else:
        form = UploadImageForm()
    return render_to_response('wiki/gallery.html', RequestContext(request, {'form': form}))

Forms.py:

class UploadImageForm(forms.ModelForm):
    class Meta:
    model = FileUploadHandler
    #image = forms.ImageField()\
    fields = ['title']

Here you didn't save it in views. Just use this:

 if request.method == 'POST':
    form = UploadImageForm(request.POST, request.FILES)
    if form.is_valid():
        newfile = FileUploadHandler(title='anything', file=request.FILES['image'])
        newfile.save()

I think you're working a little too hard. You shouldn't have to call the FileUploadHandler model directly to save the image.

First, your form should be:

class UploadImageForm(forms.ModelForm):
    class Meta:
        model = FileUploadHandler

And your view should be:

from forms import UploadImageForm

def image_upload(request):
    form = UploadImageForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()
    return render_to_response('wiki/gallery.html', RequestContext(request, {'form': form}))

Since you're using a ModelForm, you just need to save the form once it's been validated. Just make sure that the file field is visible in your template. You were excluding the 'file' field in your form earlier that's why it wasn't working.

Update: Simplified your view even more just because...

The solution might be the template:

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form }}
    <input type="submit" name="submit" value="Submit" />
</form>

Notice: enctype="multipart/form-data"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM