[Django]-Use view/form in Django to upload a multiple files

7👍

To answer your question i will try to create a foreign key to the post and i will use function views

app/models.py:

class Post(models.Model):
    #add your all other fields here execept (files)
class File(models.Model):
     post = models.ForeignKey(Post,on_delete=models.CASCADE)
     file = models.FileField(blank=True, upload_to='PN_files/%Y/%m/%d/', verbose_name="Files", validators=[validate_file_size], help_text="Allowed size is 50MB")

app/forms.py:

from .models import Post,File
class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = [#the field that you want to rendered]
class PostFileForm(PostForm): #extending form
    file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

    class Meta(PostForm.Meta):
        fields = PostForm.Meta.fields + ['file',]

app/views.py:

from .forms import PostFileForm
from .models import File

def postcreate(request):
    if request.method == 'POST':
        form=PostFileForm(request.POST or None,request.FILES or None)
        files = request.FILES.getlist('file')
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            #add everything you want to add here
            post.save()
            if files:#check if user has uploaded some files
                for f in files:
                    File.objects.create(post=post,file=f)
             
            return redirect('the-name-of-the-view')
    else:
        form = PostFileForm()
    return render(request,'the-template-you-want-to-rendered-',{'form':form})

with this you can upload many files you want.and if you don’t want the file to be required you can add "required=False" inside the PostFileForm.

Leave a comment