Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

python - How can i save Multiple items in database using FileField in Django?

i want to upload multiple files from Django FileField. The code below upload single file instead of multiple files. i also define for loop for file data but i don't understand how can i files save in database? I would be grateful for any help.

Views

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

    def form_valid(self, form):
        form.instance.author = self.request.user
        for f in self.request.FILES.getlist('file_data'):  # file_data it's an a Attribute
            instance = form.file_data = f
            instance.save()
        return super().form_valid(form)
question from:https://stackoverflow.com/questions/65862134/how-can-i-save-multiple-items-in-database-using-filefield-in-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Hello the file field can store one file (basically it stores the path of the file) but you can do it like this:

create a model for your file:

class Document(models.model):
    file = models.FileField()
    article = models.ForeignKey(Article, on_delete=models.CASCADE)

when you want to save a file just create a Document object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...