开发者

Form from Model with File Upload

I'm trying to mimic the admin interface for the Photologue app on the front end. To achieve this, I have thus far created a bit of code in the view:

def galleryuploader(request):
    GalleryFormSet = modelformset_factory(GalleryUpload)    
    if request.method == 'POST':
        formset = GalleryFormSet(request.POST, request.FILES)
        if formset.is_valid():
            formset.save()
            # do something. ... do what?
    else:
        formset = GalleryFormSet()
    return render_to_response("cms_helper/gallery_upload.html", {
        "formset": formset,
    })

and a template:

<form method="post" action="">
    {{ formset }} 
    <input type="submit" />
</form>

I'm using django's "form from models" method for generating this front-end form.

The problem: when I try to upload a file (because I am uploading photos to a photo gallery), and hit submit, it returns with a form error telling me that a required field was missing (the file).

I think I am not checking the request for any files, but even开发者_运维百科 if I were to, I'm not quite sure how to. Here's some documentation about file uploads, but I haven't been able to decipher it yet.

If you have any suggestions about how to make this upload form work, I'd be veryyy happy to hear them. Thanks in advance!


Add the enctype="multipart/form-data" attribute to your form tag. Also you'll need to actually do something with the uploaded files. Here's the example from the django docs:

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            # you'll need to loop through the uploaded files here.
            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('some/file/name.txt', 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()

(See the comment about halfway through)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜