Okay, I have messed something up in being able to display an uploaded file.
I have a form where users can add a file (image, pdf, .doc, etc) and then I want to display a link to that file.
I first created a folder in the project root called “uploads”. The structure looks like:
Project1
→ clients/
→ uploads/
------> clients_docs
----------> funny-dog.jpg
settings.py
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
urls.py (specifically the media url and Docs section)
path('<int:client_id>/doc/add', views.DocAdd.as_view(), name="doc_add"),
path('<int:client_id>/doc/<int:pk>/edit', views.DocEdit.as_view(), name="doc_edit"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
class Doc(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE)
name = models.CharField(max_length=100, default='')
file = models.FileField(upload_to="clients_docs", null=True, blank=True)
def __str__(self):
return str(self.name)
template detail
{% for doc in doc_list %}
<li><a href="{{ doc.file }}">{{ doc.name }}</a></li>
{% endfor %}
If I upload an image “funny-dog.jpg”, I can see (via the file system), that the file made it into Project1/uploads/clients_docs/funny-dog.jpg.
However, when the template renders, the url to the file looks like this:
http://127.0.0.1:8000/clients/2/clients_docs/funny-dog.jpg
Clicking the link for that gives a “404 page not found” error.
For reference, the normal path (that works) to adding a new doc looks like this:
http://127.0.0.1:8000/clients/2/doc/add
What am I doing wrong to get the link to the newly uploaded file to display correctly?