I prepared my model to create PDF filled by all the fields it includes and I try to to link generated file to the pdf = models.FileField()
. However the path to the file seems to be ok I can't reach the file through the view.
models.py:
class Lesson(models.Model):
# fields
# ...
pdf = models.FileField(upload_to = 'pdfs/', default = None, blank = True)
def render_template(self, request):
#some magic
BASE_DIR = str(Path(__file__).resolve().parent.parent)
file_name = 'myfile'
os.system(f"pdflatex -halt-on-error --output-directory={BASE_DIR}/media/pdfs {BASE_DIR}/media/tex/rendered/{file_name}")
os.system(f"rm {BASE_DIR}/media/tex/rendered/{file_name}.tex")
os.system(f"rm {BASE_DIR}/media/pdfs/{file_name}.aux")
os.system(f"rm {BASE_DIR}/media/pdfs/{file_name}.log")
return f"{BASE_DIR}/media/pdfs/{file_name}.pdf"
views.py:
def create_lesson(request):
lesson = Lesson()
lesson.pdf = lesson.render_template(request)
lesson.save()
message = {
'tag' : 'success',
'body' : "Successfully added new lesson!"
}
return JsonResponse({'message' : message})
But when putting <a href="{{ lesson.pdf }}">CLICK TO VIEW FILE</a>
the link directs to:
http://localhost:8000/docs/lessons/media/pdfs/myfile.pdf
What path should be set to pdf field to direct to media/pdf/myfile.pdf
in models.py
?
CodePudding user response:
Just use it like this:
<a href="/media/{{ lesson.pdf }}">CLICK TO VIEW FILE</a>
After using the above code, you will be redirected to this path media/pdf/myfile.pdf