简体   繁体   English

django上传多个文件,然后保存到数据库的路径

[英]django upload multiple file and then save the path to database

I want to upload multiple image files using form, and the images then save in the ./static/ , the path of the images then save to database, when I use request.FIELS.getlist("files") in for, when using the save() , there is only one image's name save in databse, and the real images not save in the ./static/ 我要使用表单上传多个图像文件,然后将图像保存在./static/ ,然后将图像的路径保存到数据库中,当我在其中使用request.FIELS.getlist("files")save() ,只有一个图像的名称保存在数据库中,而真实图像则不保存在./static/

models.py models.py

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)

view.py view.py

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})

You can use django-multiupload copying example from git. 您可以使用git中的django-multiupload复制示例。

# 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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