I'm working on a bookstore using Django. I'm trying to save each book's cover in each book created by the user using imagefield. I implemented every step in Django documentation about using imagefield but it doesn't work.
settings.py(in main project):
MEDIA_DIR = os.path.join(BASE_DIR,'media')
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
in urls.py (main project):
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("admin/", admin.site.urls),
path("", include("book.urls")),
] static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in models.py(the book app):
class books(models.Model):
cover = models.ImageField(upload_to='cover/co', blank=True)
When I want go admin I find that the photo is submitted (when I click on the photo url in database nothing is shown to me) but I don't find any created media folders and when I try to request the image in any template It isn't showed to me. when I try to click on the photo in the database in admin this is shown to me: enter image description here These are the paths of the app, project and static: enter image description here
I don't know where is the problem and how to solve it as this is my first time to use imagefiled in django model,,, it might be from the paths, the model or the urls so if there is any help.
CodePudding user response:
Remove /
at the beginning of your MEDIA_URL
.
CodePudding user response:
Simply you can try this way:
settings.py file:
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'media')
In models.py file:
class books(models.Model):
cover = models.ImageField(upload_to='cover/', blank=True) #I have removed co from here
After adding above code don't forget to migrate
Try this and see if this is solves your problem