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/'
Related
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
I am trying to create a blog and 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 (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:
from 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/")
When I check in the google chrome console, I notice that my development server tries to read my jpg file as a txt file, I think my problem is related to this anomaly. Anyone have an idea how to solve my problem ?
This is because of CORS error error, your browser URL must be the same as that of the image. For example, if your project URL is http://127.0.0.1:8000/, your images should be http://127.0.0.1:8000/media/images/about-us-2.jpg not http://localhost:8000/media/images/about-us-2.jpg
The CORS policy suggests the "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at $somesite"
you can read more about it at https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors
you can to this
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'),
)
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?
My static files only load on index page, but when navigating to another page like: examle_url/page, it returns a 404 error since it loads it like that: http://127.0.0.1:8000/categories/default/static/js/main.js, see the static loads after page
settings.py
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root/')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, '/static/base'),
)
urls.py "all my urls are in main directory and then i import views from apps"
urlpatterns = [
path('admin/', admin.site.urls),
path('profile/', profile, name="profile"),
path('', index, name="index"),
path('category/', category, name="category"),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
If it matters my load static files are all in theme.html file and is then extended in all other html files.
Any help will be greatly appreciated, thanks in advance!
You should prepend the STATIC_URL setting [Django-doc] with a slash:
# settings.py
# …
# with a leading slash
STATIC_URL = '/static/'
# …
If you do not do that, then the url will look like static/js/main.js. If the path does not start with a slash, then that is relative to path the current URL, and thus if the page is /categories/default, it will look at /categories/default/static/js/main.js.
My urls.py
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'photo.views.home', name='home'),
# url(r'^photo/', include('photo.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns('django.views.static',
(r'media/(?P<path>.*)$', 'serve', {'document_root': settings.MEDIA_ROOT}),
)
Settings.py
MEDIA_ROOT = 'E:/photo/media'
MEDIA_URL = '/media'
STATIC_ROOT = ''
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
When i try to access user uploaded images it gives me following error.
Using the URLconf defined in photo.urls, Django tried these URL patterns, in this order:
^admin/doc/
^admin/
media/(?P<path>.*)$
The current URL, images/about-landscapes-nature.jpg, didn't match any of these.
What am i doing wrong?
User uploaded images are getting stored in photo\media\images
Following is the directory structure in my Win7
photo
media
photoapp
models.py
settings.py
urls.py
I'm not sure if this'll fix all your problems, but MEDIA_URL needs a trailing slash, so it should be:
MEDIA_URL = '/media/'