Ammar rady
Ammar rady

Reputation: 146

how to override django files?

I have a function that crops user images but I don't want the model to have 2 fields so I made a function that overrides the original file and I noticed that the function works well on normal files but when I add the function to the view new file is made but at the media directory not even the the specified folder so how can i override files by Django ?

models.py

# defining directory for every patient
def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/patient_<id>/<filename>
    return 'patient_{0}/{1}'.format(instance.patient.id, filename)

class UploadedImages(models.Model):
    patient =           models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images')
    pre_analysed =      models.ImageField(upload_to = user_directory_path ,
                                            verbose_name = 'Image')
    upload_time =       models.DateTimeField(default=timezone.now)

the cropping function:

import os
from PIL import Image

def crop(corrd, file ,path,pk):

    image = Image.open(file) #To open the image as file.path won't open
    path_1 , fn = os.path.split(path) #which is MEDIA_ROOT/and <filename> 
    patient_dir = 'patient_{}'.format(pk) #to get the user directory
    path_ = path_1+patient_dir+fn #MEDIA_ROOT/patient_<id>/<filename>
    cropped_image = image.crop(corrd)
    resized_image = cropped_image.resize((384, 384), Image.ANTIALIAS)
    resized_image.save(path_)

    return path_

views.py

if form.is_valid():
            image = form.save(commit=False)
            x = float(request.POST.get('x'))
            y = float(request.POST.get('y'))
            w = float(request.POST.get('width'))
            h = float(request.POST.get('height'))
            print(x)
            print(y)
            print(w)
            print(h)
            crop((x,y,w+x,y+h),image.pre_analysed,image.pre_analysed.path)
            image.patient = patient
            messages.success(request,"Image added successfully!")
            image.save()

forms.py

class ImageForm(ModelForm):
    x = forms.FloatField(widget=forms.HiddenInput())
    y = forms.FloatField(widget=forms.HiddenInput())
    width = forms.FloatField(widget=forms.HiddenInput())
    height = forms.FloatField(widget=forms.HiddenInput())

    class Meta:
        model = UploadedImages
        fields = ('pre_analysed', 'x', 'y', 'width', 'height', )

so what do I need to do here? thanks in advance.

Upvotes: 1

Views: 185

Answers (1)

Alper
Alper

Reputation: 3973

The path you get from .path is relative to your MEDIA_ROOT folder, which may prevent your crop function from being able to open() the image file.

You can then make a new cropped file somewhere in your MEDIA_ROOT. Be sure to use os.makedirs() to create all the directories between here and the file. Also I don't see you saving the path returned from crop() back into the ImageField.

Upvotes: 1

Related Questions