How to use media files during deployment (django)? - django

Need help with managing media files during deployment.
I've read several articles and documentation regarding to subject, but can't fix my particular site: tis, this and django documentation.
Guess I've missed some obvious thing, or it could be misprint in code (link to media files).
So, I've deployed site on django, using gunicorn and nginx.
When users download some picture on site it save in media directory.
models.py
class News(models.Model):
title = models.CharField(max_length=128)
content = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
photo = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)
settings.py
DEBUG = False
...
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = []
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = 'media/'
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('news/', include('news.urls')),
...
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Try to add
urlpatterns = [...]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
but it doesn't work for me.
I guess it could be some problem in pass to media file.
I've checked link in page - it's correct.
<img src="photos/2022/05/10/kitten.jpg">
And this file is there.
Can't download picture on page.
How to download and use media files correct?
I'll be glad to get advice or link to any documentation regarding to this subject.
Thank you in advance.

Related

CKEditor in production not showing in admin panel

I've launched my project into production, CKEditior and CKEditor_uploader both worked on my local server but now doesn't show on my production admin panel. Any ideas why it may not be showing would be greatly appreciated. Or any alternative ways to implement richtext and image uploading to blog posts in django admin.
*UPDATE
I have some how got the CKEditor back but I cannot get the uploader to work, I have followed all documentation to a tee.
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/static/images/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR, '/home/martinhenso/public_html/static/images/')
STATIC_ROOT = os.path.join(BASE_DIR, '/home/martinhenso/public_html/static')
CKEDITOR_UPLOAD_PATH = "uploads/"
urls
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('martinhensonphotography.urls')),
path('ckeditor/', include('ckeditor_uploader.urls')),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT)
models
class Topic(models.Model):
title = models.CharField(max_length=100)
content = RichTextUploadingField()
def __str__(self):
return self.title
class BlogPost(models.Model):
blog_title = models.CharField(max_length=255)
blog_article = RichTextField(null=True, blank=True)
blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png")
def __str__(self):
return self.blog_title
admin
from django.contrib import admin
from . models import PostImage, EnterImage, BlogPost, Topic
# Register your models here.
admin.site.register(PostImage)
admin.site.register(BlogPost)
admin.site.register(EnterImage)
admin.site.register(Topic)
Try:
settings.py
STATIC_ROOT = [
os.path.join(BASE_DIR,'static','static_files')
]
python manage.py collectstatic
Location of static files are must be mension in nginx config file
Or
After entering the comment there will be a folder created 'static_files' inside static folder copy all the static files to to main static folder

Django Template Image not displaying even with media url and media root

Static images are showing properly. The files in the media folder are not displaying in html. I tried setting up media_url in various ways but in vain. I uploaded the image via django admin panel. The name of product is showing fine. The img.url shows /media/p2.jpg
models.py
class Product(models.Model):
name = CharField(("Name"),max_length=256,blank=False)
title_img = models.ImageField(null=True, blank=True)
settings.py
PROJECT_ROOT = (os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(PROJECT_ROOT), "media_root")
urls.py
urlpatterns = [
path('', ProductList.as_view() , name="product"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
template.html
{{p.name}}
<img src="{{p.title_img.url}}">
the name is displayed while image is not displayed. In console, I get
"GET /media/p2.jpg HTTP/1.1" 404 2690
I changed some settings and was able to resolve it. Probably the mistake was that I was changing project_root/products/urls.py instead or project_root/urls.py. Overall changes I did:
In main urls.py, added these
urlpatterns = [
path('', ProductList.as_view() , name="product"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Changed settings.py
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media/')
MEDIA_URL = '/media/'
As per the documentation: https://docs.djangoproject.com/en/3.1/howto/static-files/#serving-static-files-during-development and https://docs.djangoproject.com/en/3.1/howto/static-files/#serving-files-uploaded-by-a-user-during-development
it should be used only for development purposes,
settings.DEBUG must be set to True,
it works only if the url is local
in your case, 1 and 3 seams ok but is your DEBUG setting set to True?
As per the documentation: https://docs.djangoproject.com/fr/3.1/ref/contrib/staticfiles/#runserver, you can runserver with argument --insecure so you can still serve static files or media file with DEBUG set to False.

Django 3.1 media prefix not showing on urls

I am using Django 3.1.
settings.py looks like
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
urls.py looks like
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
my model image field looks like
dev_image_one = models.ImageField(upload_to='dev/', blank=True, null=True, verbose_name = 'image 1')
When files are uploaded, they end up in the /media/dev directory.
When they are to be displayed, the url looks like:
<img src="dev/1.png">
If I manually append /media/ on to the front of the url, the image displays. I never had this problem before so I'm at a loss as to what is going wrong. I never used 3.1 before, so I'm wondering if that doesn't have something to do with it. No problem with the static files. Thanks.
Make sure settings.py be like
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
load {% load static %} in any page that you want to access image
use {% static 'images/india.jpg' %} to acess image

Return the correct url of static file in Django

model.py:
class Album(models.Model):{
poster = models.ImageField upload_to='static/images/album/%Y/%m/%d')
}
serializer.py
class AlbumSerializer(serializers.ModelSerializer):
doc = DoctorSerializer()
class Meta:
model = Album
fields = '__all__'
setting.py
STATIC_URL = '/static/'
STATICFILES_DIRS=[
os.path.join(BASE_DIR,'static')
]
views.py
class index(viewsets.ModelViewSet):
serializer_class = AlbumSerializer
queryset = Album.objects.all()
When I upload the image under http://127.0.0.1:8008/admin/qa/album/, the image show as 'static/images/album/2018/06/27/xxxxxx.jpg' at the poster field in the database. And I can access to the image through http://127.0.0.1:8008/static/images/album/2018/06/27/xxxxxx.jpg.
However, in the index view, the Django Rest Framework API return the url of the image as:
http://127.0.0.1:8008/api/index/static/images/album/2018/06/27/xxxxxx.jpg, which make the image 404.
Why the /api/index/ has been added to the url? What's wrong with my setting? Need your help...
To propely serve media files you need to add MEDIA_URL and MEDIA_ROOT to your settings also:
MEDIA_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR,'static')
Note if you set static directory with MEDIA_ROOT setting in upload_to path you can skip static:
poster = models.ImageField(upload_to='images/album/%Y/%m/%d')
In urls.py:
from django.conf import settings
urlpatterns = [
# your urls here
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
UPD
As #brunodesthuilliers said in comment, you'd better divide media and static files and use media url and directory instead of static:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'medial')

django-photologue thumbnails not loading

I am trying to use django-photologue, I installed it and did mentioned settings.
I have a model Blog as follows:
class Blog(models.Model):
title = models.CharField(max_length=150)
thumbnail = models.ForeignKey(Photo, related_name='blogs')
I am able to add images to blog objects, however I do not see the thumbnail in my admin interface (clicking on it basically opens base.html stored in templates folder which I simply copied from example_project, this base.html is not important for me, however seeing this thumbnail could be interesting):
NOTE: I guess my MEDIA_ROOT and MDIA_URL properties are wrong, I am not sure what I should be writing there. I get
GET http://127.0.0.1:8000/photologue/photologue/photos/cache/dog_1_admin_thumbnail.jpg 404 (Not Found)
for
MEDIA_ROOT = os.path.join(BASE_DIR, 'photologue', )
MEDIA_URL = '/photologue/'
error, on my console.
My folder structure:
The thumbnails part of the question is fixed by doing following settings:
In my urls.py file I had to
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
#all urls
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And in my settings.py file I added:
STATIC_ROOT = os.path.join(BASE_DIR, 'public', 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'public', 'media')
MEDIA_URL = '/media/'