简体   繁体   中英

How can i use filepond javascript library in Django template?

Intro : I have Django web app where users are allowed to create posts. Each post has multiple images that are associated with that post.

What I want to do : I want to use Filepond javascript library for remove, add more and previews of selected images.

The issue : The code below is working ok without filepond library but if i try to use filepond library the form is submitting only title input without files.

views.py

class NewsCreateView(CreateView):
    form_class = FileForm
    template_name = 'create.html'
    success_url = '/'

    def form_valid(self, form):
        post = form.save(commit=False)
        post.author = self.request.user
        post.save()
        for f in self.request.FILES.getlist('filepond'):
            FileModel.objects.create(post=post, file=f)
        return super().form_valid(form)

create.html

<link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet">
<link href="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css" rel="stylesheet">


<div class="content">
    <div class="row">
        <div class="col-md-12">
            <div class="hpanel" style="margin-top: 10px;">
                <form method="POST" enctype="multipart/form-data">
                    {% csrf_token %}
                    <div class="form-group">
                        <input type="text" id="id_title" name="title" class="form-control">
                        <input type="file" id="id_file" name="file" multiple="true">                    
                    </div>
                    <button class=" btn btn-success btn-block" type="submit">Submit</button>
                </form>
            </div>
        </div>
    </div>
</div>
<script src="https://unpkg.com/filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.js"></script>
<script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>

<script>
    FilePond.registerPlugin(
        FilePondPluginImagePreview
    );

    FilePond.create(
        document.querySelector('input[type="file"]')
    );
</script>

It's not possible to set a file input value, see: https://pqina.nl/blog/the-trouble-with-editing-and-uploading-files-in-the-browser/

So FilePond won't update the existing file input.

You either have to upload the file asynchronously by setting the FilePond server property or use the Filepond File Encode plugin to encode the file as base64 data which can be sent to the server as a string.

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