I am trying to load a pdf file in django which is already present in the database. I can access the pdf file using the url, "localhost:8000/documents/file.pdf" but when I perform the query and return the response containing this file, url it redirects to "localhost:8000/ans/documents/file.pdf" which doesn't exist. The html code is:
<form id="signup-form" method="POST" action="ans/">
{% csrf_token %}
<input type="text" name="id" id="id" placeholder="Report id" />
<input type="submit" value="Check" />
</form>
The path in urls.py is
path('ans/',views.func),
The view is:
def func(request):
if request.method=="POST":
id=request.POST.get("id")
ans = query.objects.get(id=id)
response=ans.repo
if ans is None:
return render(request,"index.html",{})
else:
return redirect(response)
The bottomline is, I wan't to get rid of the "/ans/" in the url.
When you put
ans/
it adds this to the url and file location is added right after it. To solve the issue removeans/
and give name.Moreover, you have logical mistakes in view and form. You should have used either normal form or ModelForm to get id to form the form.
Instead of these bad design, you should have used
FileField
in your models.py class and after that you would be eligible to get the url with file.url call in any place without redirecting it and you could easily assign it to any button.Note: To skip the action attribute you should use I have mentioned above
form
and render it in the view method.Edit : Lets say you want to view the file from a specific object(You just need to pass the pk of the object which can be done with url template tag)
urls.py
view.py
Now it is time to view the uploaded file on click template.py
file.url
is the magic to retrieve the exact url of the file. so when it is clicked the file will be opened.