0

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 views.py 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
        form.save()

        if form.is_valid():
            form.lr_connected = lr_object
            form.save()
            return redirect('home')
    else:
        form = UploadPODform()
        form.lr_connected = lr_object


    return render(request, 
'classroom/suppliers/model_form_upload.html', {'form': form})

This is my forms.py 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 models.py file:

class Uploaded_pod(models.Model):
    document = models.FileField(upload_to='pods/')
    lr_connected = models.ForeignKey(LR, on_delete=models.CASCADE, 
related_name='lr_pod')

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

BPDESILVA
  • 2,040
  • 5
  • 15
  • 35
chirag
  • 153
  • 2
  • 13

1 Answers1

1

You can do it like this:

def image_path(instance, filename):
    return '/'.join(['uploads', instance.lr_connected.pk, filename])


class Uploaded_pod(models.Model):
    document = models.FileField(upload_to=image_path)
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • can you elaborate more ? What should we I put in filename ? – chirag Jul 10 '19 at 10:01
  • what should be the filename in this ? Can you please elaborate ? @ruddra – chirag Jul 10 '19 at 10:55
  • @chirag filename is a default argument for this function, you don't need to put anything for this. filename is the actual filename of the file you are uploading – ruddra Jul 10 '19 at 11:38