We have a django project in which we are storing images in the backend using image field.The image link is being stored on django admin site.However ,when I click on the link ,I get an error page.Here's my code. models.py
images=models.ImageField(upload_to=upload_to,null=True)
def upload_to(instance, filename):
return 'images/{filename}'.format(filename=filename)
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('app/',include('firstapp.urls')),
path('',include('firstapp.api.urls')),
] static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media')
# URL used to access the media
MEDIA_URL = '/media/'
I have created a folder named media but the images are not being stored there.Please help.
CodePudding user response:
From Python Doc. os.path.dirname(...)
Return the directory name of pathname path. This is the first element of the pair returned by passing path to the function split().
os.path.join()
takes first argument as full path becouse of this your MEDIA_ROOT is giving wrong path.
If you're using Django>=3.0
version then you can use pathlib
like this
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
CodePudding user response:
You can try this way:
MEDIA_ROOT=os.path.join(BASE_DIR,'media') #Just add like this
Do pass directly to field instead of creating function of uploat_to.
images=models.ImageField(upload_to="images/",null=True)
Do above things and see if it solves.
Do reply if it is not solved.