'How to get the path to your saved image in django

I created a form model using the code below

class TrainImageForm(forms.ModelForm):
    class Meta:
        model = TrainImage
        fields = (
            'image',
        )

    def customSave(self):
        lv = self.save(commit=False)
        lv.save()
        return lv.image.name

And this is how I saved uploaded image. But any time I try to retrieve the image, I get a "FileNotFoundError"

def testnetwork(request):
    if request.method == "POST":
        form = TrainImageForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            filename = str(form.customSave())
            img_array = imageio.imread("media/train_images/" + filename,as_gray=True)
            img_data = 255.0 - img_array.reshape(784)
            img_data = (img_data/255.0 * 0.99) + 0.01
            global n
            output = n.query(img_data)
            label = numpy.argmax(output)

But when I input the path of the file manually (in the imageio.imread), it works without any error. Please how do I go about this



Solution 1:[1]

https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.fields.files.FieldFile.path is the method you want if your storage backend implements it. the name is just the name.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Işık Kaplan