Accessing Uploaded files in Django

I am trying to display the urls of Multiple files I uploaded related to the post model. My settings.py 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.

# models.py
class Post(RandomIDModel):
    student = models.ForeignKey(User, on_delete=models.CASCADE)
    subject = models.CharField(null=True, blank=False, 
              max_length=50)
    deadline = models.DateTimeField(null=True, blank=False)
    description = models.TextField(null=True, blank=False)
    pages = models.IntegerField(
        validators=[MinValueValidator(1)], default=1,null=True, 
              blank=False)
    status = models.CharField(max_length=10, 
    choices=status_choices, default="pending")
    price = models.DecimalField(max_digits=10,decimal_places=2, 
             default=0.00)
    reference_style = models.CharField(
        max_length=10, choices=reference_styles, default="Apa"
    )
    number_of_references = models.IntegerField(
        validators=[MinValueValidator(1)], default=1,null=True, 
    blank=False
    )
    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, 
    related_name="attachment")

#views.py
@login_required(login_url="/account_login")
# @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, 
                          request.FILES)
        attachments = request.FILES.getlist("attachment")
        if form.is_valid() and attachment_form.is_valid():
            post = form.save(commit=False)
            post.student = request.user
            post.save()
            for f in attachments:
                post_attachment = PostAttachment(attachment=f, 
                post=post)
                post_attachment.save()
            messages.success(request, "Upload Succeessful!")
            return redirect("/dashboard")
    else:
        form = PostForm()
        attachment_form = PostAttachmentForm()
    return render(
        request,
        "main/create_post.html",
        {"form": form, "attachment_form": attachment_form},
    )


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

#post_detail.html
<td>
   <p>{{post.attachments.attachment.all}}</p>
</td>

According to the documentation (https://docs.djangoproject.com/fr/4.1/topics/files/#using-files-in-models):


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

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 %}
     <td>
        This task has no attachments!
     </td>
     {% endfor %}

I was not referencing the attachments related name properly.

Back to Top