I have this form where the user has to upload a file(receipt) and then connect that file with a foreign key. I have created a simple form which takes the file, and it is working fine too. But, I have to save that file in the database, along with a foreign key to another model. Right now my model just has the file as relation and the foreign key. My form has just the field for the file upload because I obviously do not want the user to select what foreign key it is supposed to be. I want that foreign key to be filled automatically with the value given in the URL. I am calling the function like so:
href="{% url 'suppliers:model_form_upload' quiz.id %}"
where I am getting the quiz.id
correctly.
This is my model:
class Uploaded_pod(models.Model):
document = models.FileField(upload_to='pods/')
lr_connected = models.ForeignKey(LR, on_delete=models.CASCADE, related_name='lr_pod')
What I Tried
This is my views.py function:
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})
As you can see, I am trying to fill the form.lr_connected
part with the object I just filtered using the pk value passed in the URL.
This is my form:
class UploadPODform(forms.ModelForm):
class Meta:
model = Uploaded_pod
fields = ('document',)
I printed the object lr_object
also, and it was working just fine. But, when I go the the page to upload a file, it tells me that
null value in column "lr_connected_id" violates not-null constraint DETAIL: Failing row contains (10, pods/csv_BET4hl8.svg, null).
Which clearly mens my lr_connected field was not filled by the object I tried to pass it.
Is this possible?? Is there a better way ???
I followed this guide to upload files. Is this what is complicating the issue?
This my html rendered to:
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
<p><a href="{% url 'home' %}">Return to home</a></p>
{% endblock %}
Here you can see I added print statement, and it is showing that in my terminal that it found the lr_object with 5 as the ID.