django upload multiple file and then save the path to database
<p>I want to upload multiple image files using form, and the images then save in the <code>./static/</code>, the path of the images then save to database, when I use <code>request.FIELS.getlist("files")</code> in for, when using the <code>save()</code>, there is only one image's name save in databse, and the real images not save in the <code>./static/</code></p>

<p><strong>models.py</strong></p>

<pre><code>class User(models.Model):
    username = models.CharField(max_length=200)
    headImg = models.FileField(upload_to='./upload/')
    is_excuted = models.BooleanField(default=False)
    time = models.DateField(default=timezone.now)
    score = models.DecimalField(max_digits=2, decimal_places=2, default=0.00)
</code></pre>

<p><strong>view.py</strong></p>

<pre><code>class UserForm(forms.Form):
    username = forms.CharField()

def register(request):
    if request.method == "POST":
        uf = UserForm(request.POST, request.FILES)
        if uf.is_valid():
            username = uf.cleaned_data['username']
            for f in request.FILES.getlist("files"):
                user = User()
                user.username = username
                user.headImg = f.name
                user.save()
            return HttpResponse('upload ok!')
    else:
        uf = UserForm()
    return render_to_response('register.html',{'uf':uf})
</code></pre>

<p>You can use <a href="https://github.com/Chive/django-multiupload" rel="nofollow">django-multiupload</a> copying example from git.</p>

<pre><code># forms.py
from django import forms
from multiupload.fields import MultiFileField

class UploadForm(forms.Form):
    attachments = MultiFileField(min_num=1, max_num=3, max_file_size=1024*1024*5)

    # If you need to upload media files, you can use this:
    attachments = MultiMediaField(
        min_num=1, 
        max_num=3, 
        max_file_size=1024*1024*5, 
        media_type='video'  # 'audio', 'video' or 'image'
    )

    # For images (requires Pillow for validation):
    attachments = MultiImageField(min_num=1, max_num=3, max_file_size=1024*1024*5)


# models.py
from django.db import models

class Attachment(models.Model):
    file = models.FileField(upload_to='attachments')

# views.py
from django.views.generic.edit import FormView
from .forms import UploadForm
from .models import Attachment

class UploadView(FormView):
    template_name = 'form.html'
    form_class = UploadForm
    success_url = '/done/'

    def form_valid(self, form):
        for each in form.cleaned_data['attachments']:
            Attachment.objects.create(file=each)
        return super(UploadView, self).form_valid(form)
</code></pre>

python django database