0

I'm trying to let the user upload several files in a fileuploadfield, which are processed and stored in a database.

models.py

class MyModel(Model):
    user = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE)
    title = CharField(max_length=200, default='')
    text = TextField(default='', blank=True, null=True)
    document = FileField(null=True, blank=True, upload_to="documents")

forms.py

class MyModelForm(ModelForm):
    class Meta:
        model = MyModel
        fields = [
            'document'
        ]
        labels = {
            'document': 'upload documents here'
        }
        widgets = {
            'document': ClearableFileInput(attrs={'multiple': True})
        }

views.py

    if form.is_valid():
        counter = 0
        for f in request.FILES.getlist('document'):
            instance = form2.save(commit=False)
            instance.user = request.user
            instance.title = counter
            instance.save()
            counter += 1
        return redirect('overview', num)

What happens here is that this loop keeps getting applied to only one instance for every document i upload. If I upload 3 documents, I am supposed to get three separate stored entries in the database called 0, 1, 2. But what happens is that I only get one called 2.

What am I doing wrong?

Edit:

Issue is solved by parts of answer to associated question - leading to the following functional code:

views.py

    if form.is_valid():
        counter = 0
        for f in request.FILES.getlist('document'):
            instance = MyModel.objects.create(user=request.user, title=counter)
            instance.save()
            counter += 1
        return redirect('overview', num)
LarsLill
  • 141
  • 1
  • 10
  • 1
    refer to this answer https://stackoverflow.com/a/69334720/15042684 – Thierno Amadou Sow Apr 21 '22 at 09:29
  • 1
    Great! Found the answer there. That question contains a whole lot of other context though - only one line of code needed which specifically adresses the loop(where the object is created for each loop). If you want to answer with this line added I will mark it as correct. – LarsLill Apr 21 '22 at 09:48
  • 2
    i am happy i was able to help you , you can upvote that answer from the link i sent you. – Thierno Amadou Sow Apr 21 '22 at 09:53

0 Answers0