I am aware of this question: Django Uploaded images not displayed in development , I have done everything that it is described, but still can't find a solution. I also have used for reference this: GeeksForGeeks and Uploaded Files and Uploaded Handlers - Django documentation, however, none of them solved my problem.
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.
# 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 :
# 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:
<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>
Link
</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:
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!
EDIT: The solution has been found, the Nginx was not serving the media as Daniel suggested. There is some uWSGI documentation which is worth reading to avoid further similar problems Documentation
Your Nginx is not serving the MEDIA_URL i.e. /media/. You need an Nginx configuration section like you have for /static/
server {
listen 80;
server_name <my IP> ;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/myusername/myproject;
}
location /media/ {
root /home/myusername/myproject;
}
location / {
include proxy_params;
proxy_pass http://unix:/home/myusername/myproject/myproject.sock;
}
}
You may need to run this command :
python manage.py collectstatic from the shell of your platform
if you are using heroku here is the command
heroku run python manage.py collectstatic
Related
I have setup my python project using nginx and gunicorn as described in this tutorial https://djangocentral.com/deploy-django-with-nginx-gunicorn-postgresql-and-lets-encrypt-ssl-on-ubuntu/
so far everything works perfectly fine.
My project is in /root/project_folder/
I want to upload files via the admin page, but I get a bad request error 400. The media folder I want to add the files to is /var/www/my_domain/media (owned by the group www-data). This is also properly configured since I can see the images when I move them manually into that folder.
Do you guys maybe have any idea why the issue may be ?
the main problem is when uploading I need to save the image to the media root:
/var/www/domain/media/images/dad/ProfilePicture/offline_screen.png
But when I send request to view the image the web server returns the following:
/media/var/www/domain/media/images/dad/ProfilePicture/offline_screen.png
The upload_to path needs to be images/dad/ProfilePicture/offline_screen.png for correct request but then the image is uploaded to the wrong folder
Any ideas ? Thanks in advance!
UPDATE:
Here is my nginx config
`
server {
server_name domain.net www.domain.net ip_address;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /var/www/domain;
}
location = /media/ {
root /var/www/domain;
}
location / {
include proxy_params;
proxy_pass http://unix:/var/log/gunicorn/domain.sock;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/domain/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/domain/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = www.domain) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = domain) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
server_name domain www.domain ip_address;
return 404; # managed by Certbot
}
`
Here is my media root / media url:
MEDIA_ROOT = '/var/www/domain/media' #os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
The url.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('webpages.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
And finally how I serve and upload Images:
def get_path_of_content_image(instance, filename):
return os.path.join(settings.MEDIA_ROOT, "images", str(instance.course.topic), str(instance.course), filename)
class Topic(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(max_length=445)
image = models.ImageField(upload_to=get_topic_profile_path, default="images/default.jpeg")
def __str__(self):
return self.title
def image_tag(self):
if self.image:
return mark_safe('<img src="%s" style="width: 200px; height:200px;" />' % self.image.get_image())
def get_image(self):
if self.image:
return str(self.image.url).replace('/media/var/www/domain', '') ########1
else:
return settings.STATIC_ROOT + 'webpages/img/default.jpeg'
image_tag.short_description = 'Current Image'
I wrote this line #######1 since set the upload path to the full media root but then in order to return the correct path I need to remove the media root prefix. And also very importantly this only works if DEBUg set to TRUE.
I'm not certain this will solve your issue, but there are 2 things that need to be configured correctly here. If nginx is serving the files in your media directory ok, I'm guessing your nginx config is already ok and you just need to edit settings.py, but I'll include the nginx config in case it helps someone else.
UPDATE
I don't think those methods in your models are necessary, although I don't really know how they are used. Here's an example of how I configure a model with an ImageField:
Firstly, how to upload and save images
(letting django do most of the work)
models.py
...
class Post(models.Model):
"""Represents a single blog post"""
# model fields
title = models.CharField(max_length=150, unique=True)
content = models.TextField()
title_image = models.ImageField(upload_to='image/', blank=True, null=True)
...
forms.py
...
class PostModelForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'title_image', 'content']
widgets = {
'content': Textarea(attrs={'cols': 80, 'rows': 25}),
}
...
views.py
...
def new_post(request):
context = {}
template = 'new_post.html'
# POST
if request.method == 'POST':
form = PostModelForm(request.POST or None, request.FILES)
if form.is_valid():
new_post = form.save()
return redirect('list_post')
else:
context['form'] = form
return render(request, template, context)
# GET
else:
context['form'] = PostModelForm()
return render(request, template, context)
...
new_post.html (note the enctype of the form - important if you want to upload files)
...
<div class="card bg-light">
<div class="card-header">
<h3>New Post</h3>
</div>
<div class="card-body">
<form action="{% url 'blog:new_post' %}" method="POST" class="w-100" enctype="multipart/form-data">
<div class="col-12">
{% csrf_token %}
{{ form.as_p }}
</div>
<div class="col-12">
<ul class="actions">
<button class="primary" type="submit">Save</button>
</ul>
</div>
</form>
</div>
</div>
...
Secondly, how to serve your images
Now you want to display the image in you markup
In views.py
...
def detail(request, id):
context = {}
template_name = 'post.html'
post = get_object_or_404(Post, id=id)
context['post'] = post
return render(request, template_name, context)
...
In your markup in post.html
...
{% if post.title_image %}
<span class="img"><img src="{{ post.title_image.url }}" alt="image for {{ post.title }}" /></span>
{% endif %}
...
(1) Define MEDIA_ROOT and MEDIA_URL in settings.py
In settings.py add
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Note: Read the django docs on MEDIA_ROOT and MEDIA_URL
(2) define media location in nginx server block
In that tutorial the nginx configuration doesn't define a location for media. Here's the server block from the tutorial:
server {
listen 80;
server_name server_domain_or_IP;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /path/to/staticfiles;
}
location / {
include proxy_params;
proxy_pass http://unix:/var/log/gunicorn/project_name.sock;
}
}
I think it should look something like this:
server {
listen 80;
server_name server_domain_or_IP;
location = /favicon.ico { access_log off; log_not_found off; }
location /media/ {
root /path/to/media;
}
location /static/ {
root /path/to/staticfiles;
}
location / {
include proxy_params;
proxy_pass http://unix:/var/log/gunicorn/project_name.sock;
}
}
If that configuration doesn't work, I've posted what works for me below
In my own experience with django, nginx and gunicorn however, my nginx configuration looks like this:
server {
listen 443 ssl;
listen [::]:443 ssl;
ssl_certificate /etc/letsencrypt/live/website_name.com-0001/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/website_name.com-0001/privkey.pem; # managed by Certbot
server_name website_name.com www.website_name.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /media {
alias /home/user_name/website_name/project_name/media;
}
location /static/ {
alias /home/user_name/website_name/project_name/static_root/;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
}
Note 1: Here are the nginx docs for alias and root directives.
So after spending an eternity on debugging, I have the solution to my problem:
First Thing that was problematic is the '=' between 'location' and '/media/' in the nginx file. Be sure that this is not root of the error. It should look like this:
location /media {
alias /home/user_name/website_name/project_name/media;
}
and not like this:
location = /media {
alias /home/user_name/website_name/project_name/media;
}
The file upload to a custom local directory can be done like this:
from django.core.files.storage import FileSystemStorage
fs = FileSystemStorage(location=settings.MEDIA_ROOT)
and for the model add the file storage option on upload (or change the name of the image with the updated path afterwards):
image = models.ImageField(upload_to=get_topic_profile_path, default="images/default.jpeg", storage=fs)
thanks for the other answers. I learned quite a lot by fixing this erros :D
I'm in the process of setting up an Apache web server on an Ubuntu VM using Django with the intention of configuring it for production. I used this walk-through to get Apache and Django up and running, and since, I've been following along with the official tutorial provided in the Django docs. I've gotten up to Part 6, which discusses managing static files, but I can't seem to get the styling to apply.
Abbreviated Server File Structure:
/etc/
--apache2/
----apache2.conf
....
/build/
--django/ <-- Django installation
--tstdj/ <-- target project
----manage.py
----polls/
------...
------static/
--------polls
----------styles.css
------templates/
----------....
----------index.html
------urls.py
------views.py
----static/
------....
------polls/
--------styles.css
----tstdj/
------....
------settings.py
------urls.py
------wsgi.py
/etc/apache2/apache2.conf:
....
WSGIDaemonProcess www-data processes=2 threads=12 python-path=/build/tstdj
WSGIProcessGroup www-data
WSGIRestrictEmbedded On
WSGILazyInitialization On
WSGIScriptAlias / /build/tstdj/tstdj/wsgi.py
Alias /static/ /build/tstdj/static
<Directory /build/tstdj/tstdj>
Require all granted
</Directory>
<Directory /build/tstdj/static>
Require all granted
</Directory>
<Directory /static>
Require all granted
</Directory>
/build/tstdj/tstdj/settings.py:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
....
STATIC_ROOT = BASE_DIR + '/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = [
'/build/tstdj/polls/static',
]
#STATIC_DIRS = 'static'
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
/build/tstdj/polls/templates/polls/index.html:
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/styles.css' %}">
<p><span>My name Jeff</span></p>
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question. question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
/build/tstdj/polls/static/polls/styles.css:
li a {
color: green;
}
Obviously, the desired output in this case is to have green links. The network tab of the inspector shows 403 errors on the styles.css file, as does attempting to go straight to localhost:8080/static/.
I've run python manage.py collectstatic and sudo service apache2 restart Lord knows how many times. I know there are means of getting the styling to work in development, but I've yet to get them functional for production.
My issue was that I attempting to change permissions in /etc/apache2/apache2.conf rather than /etc/apache2/sites-available/000-default.conf.
Apache 403 while serving Django static files
Background: I'm using the Django manage.py runserver for local development. I have the contrib.staticfiles in installed apps and I'm using its {% static %} template tag in my templates.
What I try to achieve: For development, I'd like to use an independent server for serving the static files but use the django development server to serve the Django app. So that I could access the page locally on my computer at http://127.0.0.1:8000, but all the static files would be served from another computer or from a different server on the localhost, as defined by the settings.STATIC_URL variable.
The problem: The settings.STATIC_URL variable is somehow overridden when I'm using the development server. So all my static files are served by the local django development server instead of what I defined in settings.STATIC_URL.
Solution: See Daniel's answer below!
settings.py:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = os.path.join('127.0.0.1:666', BASE_DIR, 'static/')
example_template.html:
{% load staticfiles %}
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript jquery=True%}
{% bootstrap_messages %}
{# Load MyApp CSS #}
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700subset=greek-ext,vietnamese,cyrillic-ext,latin-ext' rel='stylesheet' type='text/css'>
<link href="{% static 'css/my_app.main.css' %}" rel="stylesheet">
page source when using a browser:
<link href="FULL_PATH_TO_BASE_DIR_HERE/static/css/my_app.main.css" rel="stylesheet">
but expected to see:
<link href="127.0.0.1:666/FULL_PATH_TO_BASE_DIR_HERE/static/css/my_app.main.css" rel="stylesheet">
This isn't anything to do with Django or runserver. It's simply because you are using os.path.join() to join a domain and a path; that function doesn't know about URLs, and will assume that since BASE_DIR starts with a leading slash, it should normalize the whole path to start from there and ignore anything previous:
>>> os.path.join('127.0.0.1', '/foo', 'static')
'/foo/static'
The solution is twofold: don't use os.path.join on URLs, but more importantly, don't use BASE_DIR in your STATIC_URL. The filesystem directory your static files live in has nothing whatsoever to do with the URL they are exposed on. Your STATIC_URL should be something like "http://127.0.0.1:666/static/".
I currently have the function of uploading images on my site. All the images are working uploading correctly, but when I try to display them using the image.url attribute in the view, it gives me a 404 not found error.
My believe it might be something with my Apache config or Django settings.py.
In my Apache config under I have:
Alias media/ /var/www/MySite/media/
<Directory /var/www/MySite/media>
Require all granted
</Directory>
In my settings.py:
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = 'media/'
In my view I am trying to display the image as follows:
{% for photo in photos %}
<div class="col-md-3 photo-wrapper">
<img src="{{ photo.image.url }}"/>
</div>
{% endfor %}
The image then looks for this url:
http://mysite.co.za/media/profile_photos/photo.png
But it doesn't find the image.
I did check that the image gets uploaded and it does to the correct location.
Also my model for clarification:
image = models.ImageField(upload_to='profile_photos')
Note: This is working fine when I work with the site on my localhost.
Edit:
So while I was trying different fixes I messed up some stuff that caused me to change the Debug in the settings.py to True, then I saw the image was actually being shown. I changed the debug to false again and the image was once again not showing. What would cause dubug to influence this?
The apache alias directive should start with a /
Alias /media/ /var/www/MySite/media/
I am trying to add an image to my simple google app engine code, but it doesn't work if I follow the tutorial. It works if my image is in my app directory, but not when I move it to static.
When I am using it in plain html like:
<img src="../static/myimage.jpg"></img>
or
and many other variations, the image just does not show (it shows when it is outside of static dir). When I am doing it as in the tutorial, defining STATIC_URL in my settings file:
STATIC_URL = '/static/'
And adding this lines (or variations like "/my_image.jpg" and so on)
{% load staticfiles %}
<img src="{% static "my-app/myimage.jpg" %}" alt="My image"/>
causes server error (500). I am using django 1.3
Here is the directory structure:
my-app
\static
myimage.jpg
\templates
base.html
# and other html files
\urls.py, settings.py #and other .py files
App.yaml:
-url: /(.*\.(gif|png|jpg))
static_files: static/\1
upload: static/(.*\.(gif|png|jpg))
setting.py:
ROOT_URLCONF = 'urls'
urls.py:
STATIC_URL = '/static/'
What did you set STATIC_ROOT to?
Generally though, using GAE's static file handlers in app.yaml will give you better caching and probably lower cost than serving the images with django's staticfiles.