Trying to use django and dropzone/

冷暖自知 提交于 2019-12-03 03:47:09
Alban Dumouilla

You can handle Dropzone posts like any other multipart form post.

Here's how I proceed:

@login_required
@usertype_required
def upload_picture(request, uid=None):
    """
    Photo upload / dropzone handler
    :param request:
    :param uid: Optional picture UID when re-uploading a file.
    :return:
    """
    form = PhotoUploadForm(request.POST, request.FILES or None)
    if form.is_valid():
        pic = request.FILES['file']
        # [...] Process whatever you do with that file there. I resize it, create thumbnails, etc.
        # Get an instance of picture model (defined below) 
        picture = ...         
        picture.file = pic
        picture.save()
        return HttpResponse('Image upload succeeded.')
    return HttpResponseBadRequest("Image upload form not valid.")

The form is dead simple

class PhotoUploadForm(forms.Form):
    # Keep name to 'file' because that's what Dropzone is using
    file = forms.ImageField(required=True)

In your model you need the upload_to set:

class Picture(models.Model):
    [...]
    # Original
    file = models.ImageField(upload_to=get_upload_path)

And here's my upload path builder, but you can put anything

def get_upload_path(instance, filename):
    """ creates unique-Path & filename for upload """
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (instance.p_uid, ext)
    d = datetime.date.today()
    username = instance.author.username

    #Create the directory structure
    return os.path.join(
        'userpics', username, d.strftime('%Y'), d.strftime('%m'), filename
    )

Don't forget the csrf_token in the html form itself (I'm using an angularJS directive on top of it so will be different for you)

<form action="{% url 'upload_picture' %}" class="dropzone" drop-zone>
    {% csrf_token %}
    <div class="fallback">
        <h3>Your browser is not supported.</h3>
        <strong>
            <a href="https://browser-update.org/update.html" target="_blank">Click here for instructions on how to update it.</a>
        </strong>
        <p>You can still try to upload your pictures through this form: </p>
        <p>
            <input name="file" type="file" multiple />
            <input type="submit" value="Upload" />
        </p>
     </div>
 </form>

I got dropzone js working by modifying the bootstrap example (I am using bootstrap) here: http://www.dropzonejs.com/bootstrap.html

I do not use any forms. I got a view handling the in coming ajax posts from dropzone. Here is the gist of my view code:

class AjaxUploadView(View):
    """
        View for uploading via AJAX.
    """
    def post_ajax(self, request, *args, **kwargs):
        uploaded_file = request.FILES['file']
        # Do stuff with file
        # Return appropriate response

Hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!