problem in loading media files into templates - django

My django project is searching for images in
/profile/<pk>/myapp/profile_pics/images.jpg
instead of myapp/profile_pics/images.jpg
similar to this question image isn't uploaded to media root using Django
settings.py -
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py -
urlpatterns = [
path('profile/<int:pk>/', views.profile, name='profile'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
views.py-
def profile(request, pk):
user = get_object_or_404(User, pk=pk)
return render(request, 'myapp/profile.html',{'account': user})
Where's the problem?

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 : Media Images not displayed in templates

I am trying to create a blog and to display image for each post. i am trying to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for Post images with an ImageField), the image is stored in /media/images correctly. But I can't display the image on my webpage. However, when I inspect my template with GoogleChrome, the path of my files are ok but there is a 500 error (about-us-2.jpg:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error).
Media Settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'core/static'),
)
Project urls.py:
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin' , admin.site.urls),
path("", include("authentication.urls")),
path("", include("app.urls")),
]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
App urls.py:
rom django.urls import path, re_path
from django.conf.urls import include, url
from app import views
from . import views
urlpatterns = [
path('', views.index, name='home'),
url(r'^blog$', views.blog_view, name ='blog'),
url(r'^blog/(?P<id>[0-9]+)$', views.post_view, name ='blog_post'),
re_path(r'^.*\.*', views.pages, name='pages'),
]
Views.py
def blog_view(request):
query = Post.objects.all().order_by('-date')
context = {'post_list' : query}
return render(request, 'blog/blog.html', context)
template : Blog.html
{% for post in post_list %}
<img src="{{ post.image.url }}" class="card-img-top rounded-top">
{% endfor %}
models.py
class Post(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255, blank=True)
image = models.ImageField(blank=True, upload_to="images/")
Try this approach:
MEDIA_ROOT = os.path.join(BASE_DIR, "APPName", "media")
MEDIA_URL = "/media/"
You can then find images under:
<img src="media/test.png">
The folder "media" is in the main dir of the Project (not the app!):
Project
media
static
APP
templates
views.py

Image Doesn't display in django from sqlite3 databbase

I am creating a website that should display several images, but none is displayed.
I have tried several ways to solve it but no changes,
image's URL is saved in sqlite db
views.py
def add_story(request):
if request.method == "POST":
form = StoryCreate(request.POST, request.FILES)
if form.is_valid():
storyitem = form.save(commit=False)
storyitem.save()
else:
form = StoryCreate()
return render(request, 'story_form.html', {'form':form})
urls.py
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root= settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)
settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_ROOT = os.path.join(SITE_ROOT, 'statics')
MEDIA_URL = '/media/'
html
<img name="Story" style="height: 100px; width: 100px" src="{{item.LogoUrl.url}}"/>

Django, React, Redux: Serving up images

I'm using a React/Redux frontend and a Django backend for a little project. I'm not using anything but the standard Django server for development. I'm trying to add an image field to an already existing UserProfile model. Currently I've got everything working except that Django won't properly serve up my images to either to the main React site or the admin site. When I either attempt to navigate to the url in question or use the Python requests library to directly request the media, the response is of type 'text/html'. Currently my model has the following field:
models.py
class UserProfile(models.Model):
...
...
profile_image = models.ImageField(upload_to='path_to_media')
project urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/account/', include('account.urls')),
url(r'^api/post/', include('post.urls')),
url(r'.*', views.root, name='root')
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'nattr'),
)
account urls.py
urlpatterns = (
...,
url(r'^edit_profile/(?P<user_id>[^/]+)/$',
views.edit_profile,
name='edit_profile'),
)
account views.py
def edit_profile(request, user_id):
try:
user = User.objects.get(pk=user_id)
form = UserProfileForm(request.POST, request.FILES, instance=user.profile, user=request.user)
valid = form.is_valid()
if valid:
profile = form.save()
return JsonResponse(profile.to_user())
else:
return JsonResponse({'errors': form.errors}, status=400)
except User.DoesNotExist:
return JsonResponse({'errors': 'cannot find user with that id'}, status=400)
What am I doing wrong? I've assigned my media_url & media_root; I've added the media urls to my urlpatterns. My view and form are pretty standard and I can see that the images are being uploaded to the folder structure
Django URL patterns are processed in order. You have .* before settings.MEDIA_URL so every URL, no matter what, will be caught by it. You should move the static URL above .*.
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/account/', include('account.urls')),
url(r'^api/post/', include('post.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# make sure this is always last
urlpatterns += [url(r'.*', views.root, name='root')]
Add the following in your urlpatterns
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
And also add this to your settings.py
ENV_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(ENV_PATH, 'media/')
MEDIA_URL = '/media/'

images aren't displayed on the admin

I'm following the django page which explains how to display images https://docs.djangoproject.com/en/1.6/howto/static-files/
And I think that I did all what's specified such as:
settings.py
STATIC_ROOT = BASE_DIR + '/static'
STATIC_URL = '/static/'
INSTALLED_APPS += ('django.contrib.staticfiles',)
models.py
image = models.ImageField(upload_to="static/my_app/")
def image_tag(self):
if self.image:
return u'<img src="{0}" />'.format("/" + self.image.url)
urls.py
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
admin.py
list_display = ('description', 'image_tag',)
But my image is not showing up.
What am I missing?