Accessing Uploaded files in Django

I am trying to display the urls of Multiple files I uploaded related to the post model. My is well set up and the files gets uploaded to the target directory. How can I access the urls of these files and print them on the post details page? This is because I want an individual to be able to download these files. So far I have tried the following.

class Post(RandomIDModel):
    student = models.ForeignKey(User, on_delete=models.CASCADE)
    subject = models.CharField(null=True, blank=False, 
    deadline = models.DateTimeField(null=True, blank=False)
    description = models.TextField(null=True, blank=False)
    pages = models.IntegerField(
        validators=[MinValueValidator(1)], default=1,null=True, 
    status = models.CharField(max_length=10, 
    choices=status_choices, default="pending")
    price = models.DecimalField(max_digits=10,decimal_places=2, 
    reference_style = models.CharField(
        max_length=10, choices=reference_styles, default="Apa"
    number_of_references = models.IntegerField(
        validators=[MinValueValidator(1)], default=1,null=True, 
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return str(self.subject)

# New form multiple file upload class.
class PostAttachment(models.Model):
    attachment = models.FileField(upload_to="atlogin", 
    blank=True, null=True)
    post = models.ForeignKey(Post, on_delete=models.CASCADE, 
# @permission_required("main.add_post", login_url="/account_login", raise_exception=True)
def create_post(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        attachment_form = PostAttachmentForm(request.POST, 
        attachments = request.FILES.getlist("attachment")
        if form.is_valid() and attachment_form.is_valid():
            post =
            post.student = request.user
            for f in attachments:
                post_attachment = PostAttachment(attachment=f, 
            messages.success(request, "Upload Succeessful!")
            return redirect("/dashboard")
        form = PostForm()
        attachment_form = PostAttachmentForm()
    return render(
        {"form": form, "attachment_form": attachment_form},

class PostDetailView(DetailView):
    model = Post
    context_object_name = "post"
    template_name = "main/post_detail.html"


According to the documentation (

   {% for attachment in post.attachments.attachment.all %}
   <a href="{{attachment.url}}">{{attachment.path}}</a>
   {% endfor %}

I am finally able to solve it. Below is the code.

    <td><i class="fa-solid fa-folder"></i>Attachment:</td>
    {% for attachment in post.attachments.all %}
     <td><a href="{{attachment.attachment.url}}">{{attachment.attachment}}</a></td>
    {% empty %}
        This task has no attachments!
     {% endfor %}

I was not referencing the attachments related name properly.

Back to Top