Django Uploaded images not displayed in production

4,179 views
Skip to first unread message

Anton Nyagolov

unread,
Jun 21, 2020, 5:00:14 PM6/21/20
to Django users
Hello everyone, I just discovered this group through Google.I couldn't get any help on stack overflow and hopefully someone here can help.

I have deployed a Django App on a Ubuntu server for the first time using Nginx and gunicorn.
Before deployment, I used port 8000 to test if everything runs as it is supposed to and all was fine. Since I allowed 'Nginx Full' my database images are not showing up.

This is my django project structure:



My virtual environment folder and my main project folder are both in the same directory. I have separated them.

```python
# Create your models here.
class Project(models.Model):
    project_name = models.CharField(max_length=120)
    project_description = models.CharField(max_length=400)
    project_link = models.CharField(max_length=500)
    project_image = models.ImageField(upload_to='')

    def __str__(self):
        return self.project_name
```
I have set up my settings.py to :
```python
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')


MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), '..', 'media').replace('\\','/')
```

My view gets all the project object from a database and passes those to the template. The template renders successfully all other information related to project model except the image field . In my template I do:
```html
 <div class="row text-center mx-auto">

        {% for project in projects %}
        {% if forloop.counter|mod:2 == 0 %}
        <div class="col projects pb-3 pt-3 mb-3 ml-2">
          {% else %}
          <div class="col projects pb-3 pt-3 mb-3 mr-2">
            {% endif %}

            <img class="card-img-top pt-2 pl-2 pr-2" src="{{ project.project_image.url}}"
              alt="Image could not be found :(" style="height:120px; width:166px !important;" /><br>
            <div class="card-body">
              <h3 class="card-title ">{{ project.project_name }}</h3>
              <p class="card-text dates">{{ project.project_description}}</p>
              <a href="{{ project.project_link }}" class="btn btn-dark" target="_blank">Link</a>

            </div>
          </div>

          {% if forloop.counter|mod:2 == 0 %}
          <div class="w-100"></div>
          {% endif %}
          {% endfor%}
        </div>
      </div>
```
Uploading the images works, it sends them in the project's media directory, the problem is that they are not showing up, the alt="" is activated.


My main urls.py:
```python
urlpatterns = [
     path('', include('project.urls')),
    path('admin/', admin.site.urls),
]  + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
```
The gunicorn system file:
```

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=myusername
Group=www-data
WorkingDirectory=/home/myusername/myproject
ExecStart=/home/myusername/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/myusername/myproject/myproject.sock myproject.wsgi:application

[Install]
WantedBy=multi-user.target

```
Nginx setup:
```
  server {
        listen 80;
        server_name <my IP> ;
        location = /favicon.ico { access_log off; log_not_found off; }
        location /static/ {
            root /home/myusername/myproject;
        }
        location / {
            include proxy_params;
            proxy_pass http://unix:/home/myusername/myproject/myproject.sock;
        }
    }
```


EDIT: When inspecting the image element of the webpage the source of the image it is "/media/imageNmae.png".
Any help would be appreciated!

Anton Nyagolov

unread,
Jun 21, 2020, 5:06:57 PM6/21/20
to Django users


On Sunday, 21 June 2020 18:00:14 UTC+1, Anton Nyagolov wrote:
Hello everyone, I just discovered this group through Google.I couldn't get any help on stack overflow and hopefully someone here can help.

I have deployed a Django App on a Ubuntu server for the first time using Nginx and gunicorn.
Before deployment, I used port 8000 to test if everything runs as it is supposed to and all was fine. Since I allowed 'Nginx Full' my database images are not showing up.

This is my django project structure:



My virtual environment folder and my main project folder are both in the same directory. I have separated them.

I have set up my settings.py to :
 


My view gets all the project object from a database and passes those to the template. The template renders successfully all other information related to project model except the image field . In my template I do:


Uploading the images works, it sends them in the project's media directory, the problem is that they are not showing up, the alt="" is activated.


My main urls.py:

The gunicorn system file:



 


Nginx setup:

Vishesh Mangla

unread,
Jun 21, 2020, 5:10:08 PM6/21/20
to django...@googlegroups.com

Hi, first of all welcome on this group. Secondly you can also try https://webchat.freenode.net/  on the #django channel but you first need to register there by asking on #freenode channel. Regarding your problem, images are static files and you should put them in static/<appname>/your_desired_path to be detectable not media if they are part of your templates. Use src={% url “your_desired_path %} and don’t forget to put {% load static %} at the top of your template.

 

Sent from Mail for Windows 10

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/635fcf7e-6e53-425d-aad1-8638fef425c1o%40googlegroups.com.

 

Anton Nyagolov

unread,
Jun 21, 2020, 5:15:43 PM6/21/20
to Django users
Thanks I will check out the group too for future reference and etc. Those images are uploaded to a database and are part of a model. I iterate through all the object and for each object I print some information including the images, therefore I cannot specify only one specific image. I use admin so I can add my (new future) projects and only by admin they should be able to display automatically on my website with all the information and structure required.
Do you sugest changing the value of the imageField (upload_to="static/<appname>/my_desired_path) ?

Vishesh Mangla

unread,
Jun 21, 2020, 5:41:08 PM6/21/20
to django...@googlegroups.com

Sorry, I misunderstood your problem. But can you also show your views.py. Also your path to MEDIA_ROOT is obfuscated. I used MEDIA_ROOT = os.path.join(BASE_DIR, 'media'). I thing this shall be sufficient to do for a try.

 

Sent from Mail for Windows 10

 

--

You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

Rob Riedlinger

unread,
Jun 21, 2020, 6:11:10 PM6/21/20
to Django users
Check out this video  https://youtu.be/kBwhtEIXGII  Denis talks about why this happens

Vishesh Mangla

unread,
Jun 21, 2020, 6:23:31 PM6/21/20
to django...@googlegroups.com

If the issue is managing static files on the server simply installing Django-heroku saved me from all that trouble.

 

Sent from Mail for Windows 10

 

From: Rob Riedlinger
Sent: 21 June 2020 23:40
To: Django users

--

You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

MUGOYA DIHFAHSIH

unread,
Jun 21, 2020, 6:54:23 PM6/21/20
to django...@googlegroups.com
Actually me too i have the same problem, i have deployed django web app on a shared host with apache linux server, and am stuck on how to serve media files, static files like js, css, and static images not from database load well.

But the problem is that when i submit a form that has an imagefield with it, it throws an error message, "404" page not found.
If anyone can help me please.

Anton Nyagolov

unread,
Jun 21, 2020, 7:09:35 PM6/21/20
to Django users
So guys I have found the problem. My Nginx server was only serving static files but not media ones, I have probably forgot about it.
My Nginx settings were:
The only thing I had to do is add a location for the media folder:


@MUGOYA DIHFAHSIH
At the begging of setting the server I also used apache2, it was pain in the ass and I switched to Nguix and Gunicorn. Setting the server over apache took me like 60-70 steps. With Nguix and Gunicorn it takes only 20 steps, for 15 min you are all set up.
Watch this video and follow the guy: How to Deploy Python-Django serveer in 20 min

MUGOYA DIHFAHSIH

unread,
Jun 23, 2020, 5:21:04 AM6/23/20
to django...@googlegroups.com
thanks Anton, i will also give nginx a try but currently the client has a domain with namecheap with shared host plan and that is where he wants me to deploy the application but name cheap has apache web server


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages