path in FileField django


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.

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"

def create_lesson(request):
    lesson = Lesson()
    lesson.pdf = lesson.render_template(request)
    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:

What path should be set to pdf field to direct to media/pdf/myfile.pdf in

Asked By: DrJoe



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

Answered By: Manoj Tolagekar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.