Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (45.3k points)

I'm trying to upload a file in Django such that uploaded file is linked to a foreign key. i.e. if I upload a file then in the database it should reflect that with which database subject it is related to

This is my file:

def pod_upload (request, pk):

    lr_object = get_object_or_404(LR, id=pk)

    if request.method == 'POST':

        form = UploadPODform(request.POST, request.FILES)

        form.lr_connected = lr_object

        if form.is_valid():

            form.lr_connected = lr_object


            return redirect('home')


        form = UploadPODform()

        form.lr_connected = lr_object

    return render(request, 

'classroom/suppliers/model_form_upload.html', {'form': form})

This is my file:

class UploadPODform(forms.ModelForm):

    class Meta:

        model = Uploaded_pod

        fields = ('document',)

        def __init__ (self, *args, **kwargs):

            super(UploadPODform, self).__init__(*args, **kwargs)  # 

self.fields['lr_connected'].required = False

This is my file:

class Uploaded_pod(models.Model):

    document = models.FileField(upload_to='pods/')

    lr_connected = models.ForeignKey(LR, on_delete=models.CASCADE, 


I expect that if some user uploads a file then it must be saved with respect to the LR object.

1 Answer

0 votes
by (16.8k points)

Basically, the filename is a default argument for this function, you don't need to put anything for this. Simply use this code there and filename is the actual filename of the file you are uploading, just try this code once:

def image_path(instance, filename):

    return '/'.join(['uploads',, filename])

class Uploaded_pod(models.Model):

    document = models.FileField(upload_to=image_path)

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers


108k users

Browse Categories