Displaying Django images: view and model want conflicting static root directories

Viewed 25

I have a simple model that holds a static image:

DjangoProject/projects/models.py

class Project(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    tags = models.CharField(max_length=30)
    image = models.FilePathField(path='projects/static/img')
    github_link = models.CharField(max_length=100, default='None')

You can see that the image path points to the static folder that contains the images to display. The static folder "img" is located in that path shown there.

Here's the template that displays the image with bootstrap cards. It just calls {% static projects.image %} as it's src.

DjangoProject/projects/templates/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-6">
        <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">
                    See Details
                </a>
            </div>
        </div>
    </div>
    {% endfor %}
</div>
{% endblock %}

With the path /projects/static/img I can use the admin page to edit the object, but any image I select won't work. Why? Because the view wants the relative path, for instance, img/somephoto.jpg . If it's the full path, projects/static/img/somephoto.jpg, it won't work.

But, if I change the model to not include the full path to the static file and say replace it with:

image = models.FilePathField(path='/img')

Then the image will work if I define it directly through the shell, but I can't use the admin page at all. It raises a FileNotFoundError with: [Errno 2] No such file or directory: '/img'. It wants the full path.

So, these two aren't getting along. How can I fix it?

My settings.py just has

STATIC_URL = '/static/'

I tried messing around with this root but it didn't seem to affect the problem. Then again, it seems important for a problem related with static dirs.

0 Answers
Related