I've been following the django 2 official tutorial but I'm a bit confused as how to work with images and uploaded files.
I have a project with a few apps. Let's call the project myProj and the app myApp. There is a model in myApp called myModel which has an image field myImage. Here is my model:
from django.db import models
class myModel(models.Model):
myImage = models.ImageField(upload_to='myApp_images')
Here is my template:
<img src="{{ n.image }}"></img>
Here is my view
from django.shortcuts import get_object_or_404, render
from .models import myModel
def index(request):
n = myModel.objects[0]
context = {
'n': n,
}
return render(request, 'myModel/index.html', context)
And here is my settings:(parts I thought were relevant)
INSTALLED_APPS = [
'news.apps.myModelConfig',
'django.contrib.staticfiles',
]
MEDIA_URL = '/media/'
MEDIA_ROOT = '/home/aran/myfiles/projects/futureCoin/media/'
Here is my myProject/urls.py:
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('myModel/', include('myModel.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
So I made an instance of the model through the django admin site. Here is the directory tree after that(I removed the pycache):
.
├── myProject
│ ├── __init__.py
│ ├── models.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
├── media
│ └── myModel_images
│ └── myImage.jpeg
├── myModel
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── __init__.py
│ ├── models.py
│ ├── static
│ │ └── myModel
│ │ ├── images
│ │ │ └── bg.jpg
│ │ └── style.css
│ ├── templates
│ │ └── myModel
│ │ └── index.html
│ ├── tests.py
│ ├── urls.py
│ └── views.py
Now the problem is that when I try to open the index page the image is not shown because the url to it is: http://127.0.0.1:8000/myModel/myModel_images/myImage.jpg
however if I manualy open the url:http://127.0.0.1:8000/media/myModel_images/myImage.jpg
I see the right Image. Can anyone please help me understand where the problem is and how I can fix it? Any other feedback on my code would also be much appreciated.