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.