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
1.1k views
in Technique[技术] by (71.8m points)

python - Django ManyToManyField getting Field 'id' expected a number but got b'x89PNG

I want to upload multiple files in Django. The code below getting Error Field 'id' expected a number but got b'x89PNG '. 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>
question from:https://stackoverflow.com/questions/65885719/django-manytomanyfield-getting-field-id-expected-a-number-but-got-b-x89png-r

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

1 Answer

0 votes
by (71.8m points)

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/


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

...