afi
afi

Reputation: 603

Django ManyToManyField getting Field 'id' expected a number but got b'\x89PNG\r\n

I want to upload multiple files in Django. The code below getting Error Field 'id' expected a number but got b'\x89PNG\r\n'. i want to use ManyToManyField as FileField. please i need the solution. I would be grateful for any help.

models.py

class FileModel(models.Model):
    filename = models.FileField(upload_to='files/')

class FileUploadModel(models.Model):
    file = models.ManyToManyField(FileModel)

froms.py

class FileUploadingForm(forms.ModelForm):
    file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False)

    def __init__(self, *args, **kwargs):
        super(FileUploadingForm, self).__init__(*args, **kwargs)

    class Meta:
        model = FileUploadModel
        fields = ['file']

views.py

def uploading_view(request):
    if request.method == "POST":
        form = FileUploadingForm(request.POST, request.FILES)
        if form.is_valid():
            # post = form.save(commit=False)
            for files in request.FILES.getlist("filename"):
                f = FileModel(filename=files)
                f.save()
            form.save()
            return HttpResponse('success')
    else:
        form = FileUploadingForm()
    return render(request, 'uploading.html', {'form': form})

HTML

<form action="." method="POST" enctype="multipart/form-data">

    {% csrf_token %}
    {{form.as_p}}
    <button type="submit">Submit</button>

</form>

Upvotes: 1

Views: 284

Answers (1)

rahul.m
rahul.m

Reputation: 5854

you can't save data like this f = FileModel(filename=files)

try this

for files in request.FILES.getlist("filename"):
    f = FileModel.objects.create(filename=files)
    f.save()

Read this https://docs.djangoproject.com/en/3.1/topics/db/models/

Upvotes: 1

Related Questions