I've read through a few answers/articles at these links, but am still confused as all of them SEEM to be slightly different than what I'm after:
I am looking to make use of Django's ImageField
function for uploading images from my admin page, to my portfolio/blog's app space. My folder structure looks like this:
Portfolio_Blog_Website
|---personal_portfolio_project
|---projects_app
|---migrations
|---static
|---img
|---templates
So I want to upload images to/display on the template from, the app > static > img folder.
Currently, I have STATIC_URL = 'static/'
set, and I'm manually drag and dropping image files into that folder, and using models.FilePathField(path="/img")
in the model, and displaying them (in a for loop) with <img src="{% static project.image %}">
, which works. I want to switch to be able to upload images from the admin page, and then display them on the app's page like they're supposed to.
From what I've read, we have to define a MEDIA_ROOT
and MEDIA_URL
variable to use with models.ImageField(upload_to="img/")
. The problem I see is that MEDIA_ROOT
needs to be an ABSOLUTE path to the folder, which I COULD set as \\C:\Portfolio_Blog_Website\projects_app\static\img
, however this isn't necessarily what I want because I'm specifically targeting the one specific app's path, but I don't want to upload images from other app's to that path also, so how can I make this work? I want each app to have its own static > img
folders, and then from the admin page, I can upload to those specific app's directories, and then display them on each app's page.
In addition to my folder structure shown above, here's some other details that should help:
personal_portfolio_project > settings.py
STATIC_URL = 'static/'
MEDIA_URL = "/img/" # This doesn't work
MEDIA_ROOT = BASE_DIR # This doesn't work
projects_app > models.py
from django.db import models
# Create your models here.
# Portfolio project overview model
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
# image = models.FilePathField(path="/img") # works as /static/img, this works with STATIC_URL
image = models.ImageField(upload_to="img/") # This doesn't work
projects_app > project_index.html
{% extends "base.html" %}
{% load static %}
{% block page_content %}
<h1>Projects</h1>
<div class="row">
{% for project in projects %}
<div class="col-md-4">
<div class="card mb-2">
<img class="card-img-top" src="{% static project.image %}">
<div class="card-body">
<h5 class="card-title">{{ project.title }}</h5>
<p class="card-text">{{ project.description }}</p>
<a href="{% url 'project_detail' project.pk %}" class="btn btn-primary">
Read More
</a>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}