I can upload images in Django admin and they appear in the correct directory, but when I have these issues when I try to view them in my templates:
{% if city.main_image %} returns false in my template
{{ city.main_image.url }} returns nothing
{{ city.main_image }} returns None
When I click the admin preview I get this 404:
Request URL: http://127.0.0.1:8000/admin/search/city/1/test/test.jpg/
city object with primary key u'1/test/test.jpg' does not exist.
The rest of the template outputs the correct information associated with the city object.
Here are my settings.py urls:
MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), "html/static")
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
My urls.py:
from django.conf.urls.defaults import patterns, include, url
from test import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('test.search.views',
url('^search/$', 'search', name="home_page"),
url(r'^(\d+)/$', 'city', name="city_page"),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
My models.py:
class City(models.Model):
name = models.TextField("Course Name", blank=False)
address = models.TextField("Address", blank=False)
city = models.TextField("City", blank=False)
state = models.TextField("State", blank=False)
country = models.TextField("Country", blank=False)
main_image = models.ImageField(upload_to="test", blank=True)
Can anyone spot what I'm doing wrong here?
Interesting, after re-syncing my database I'm no longer having issues.
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 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
locally its working fine there is no error
when i deploy django on cpanel(shared hosting) all things are working fine
but when i submit the form without image it submitted successfully.
if i choose an image and submit the form. will get page not found (404) error
i tried to disable imageField from models.py and from every place where it has used. then i checked its working fine with imageField its not working
i have changed the media_root and media_url with static_root and url. but still its not working.
models.py
from django.db import models
from django.urls import reverse_lazy
# Create your models here.
class Eventz(models.Model):
name = models.CharField(max_length=50)
image = models.ImageField(upload_to='events')
class Meta:
ordering = ['-id']
db_table = 'eventz'
def get_absolute_url(self):
return reverse_lazy('eventz')
def __str__(self):
return self.name
views.py
from django.shortcuts import render
from django.views.generic import CreateView, UpdateView, DeleteView, ListView, TemplateView, RedirectView
from .models import Eventz
class EventzCreate(CreateView):
model = Eventz
fields = ['name', 'image']
template_name = 'events.html'
def get_context_data(self, **kwargs):
context = super(EventzCreate, self).get_context_data(**kwargs)
context['events'] = Eventz.objects.all()
return context
urls.py
from django.contrib import admin
from django.urls import path, include
from . import settings
from django.contrib.staticfiles.urls import static
from upload import views
from dashboard1.views import EventzCreate
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.UploadCreate.as_view(), name="upload" ),
path('eventz/', EventzCreate.as_view(), name='eventz'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = '/home/intelexcel/public_html/static'
MEDIA_URL = '/media/'
MEDIA_ROOT = '/home/intelexcel/public_html/media'
# LOGOUT_REDIRECT_URL = 'login'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
events.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form.name}}
{{form.image}}
<input type="submit" value="Save">
</form>
The name you gave to your url page for event is eventz, but in your url bar there is pattern event.
In your urls.py you should have something like:
path('event', views.event, name="eventz"),
change it to:
path('event', views.event, name="event"),
and it should work.
update your urls list with media url path something like this :-
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
update your setting.py like this
MEDIA_ROOT = '/home/dan/mysite/media/'
MEDIA_URL = '/media/'
try to execute.
python manage.py collectstatic
there was an error with path.
i have changed the action url of my form
if the form will be submit on
sec.intelexcel.com/event
i changed the action when form is submitted
sec.intelexcel.com/eventz/eventz/
it works for me
<form action="/eventz/eventz/" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form.name}}
{{form.image}}
<input type="submit" value="Save">
</form>
urls.py
from django.contrib import admin
from django.urls import path, include
from . import settings
from django.contrib.staticfiles.urls import static
from upload import views
from dashboard1.views import EventzCreate
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.UploadCreate.as_view(), name="upload" ),
path('eventz/', EventzCreate.as_view(), name='eventz'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
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/'
I made a project using Django 1.5.4 and have now a problem with serving files being uploaded locally. My urls.py look like this now:
urlpatterns = patterns('',
url(r'^$', views.home),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.MEDIA_ROOT, document_root='')
In models.py there is an ImageField of a class Product:
photo = models.ImageField(upload_to=MEDIA_ROOT)
and a method for displaying it:
def display_photo(self):
return '<img src="%s" />' % (self.photo)
display_photo.short_description = 'Photo of a product'
display_photo.allow_tags = True
And, finally, MEDIA_ROOT in settings.py:
MEDIA_ROOT = '/home/nervosa/DjangoProjects/Sit_test/uploads/'
Still firebug shows an error:
GET http://127.0.0.1:8000/home/nervosa/DjangoProjects/Sit_test/uploads/cover.jpg 404 (NOT FOUND)
What did i do wrong?
Solved. I just needed to modify urls.py:
urlpatterns = patterns('',
url(r'^$', views.home),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^uploads/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
The whole class Product contained by models.py now looks like this:
class Product(models.Model):
title = models.CharField(max_length=50)
height = models.FloatField(max_length=10)
weight = models.FloatField(max_length=10)
color = models.CharField(max_length=7)
photo = models.ImageField(upload_to='products_photo/')
thumbnail = ThumbnailerImageField(default='', upload_to='products_photo_thumbnails')
def __unicode__(self):
return self.title
def display_photo(self):
return '<img src="%s" />' % (self.photo.url)
display_photo.short_description = 'Photo of a product'
display_photo.allow_tags = True
Sorry for not providing my ModelAdmin - here it is:
class ProductAdmin(admin.ModelAdmin):
fieldsets = [
('Title of a product', {'fields':['title']}),
('Parameters of a product', {'fields':['height', 'weight', 'color']}),
('Upload a photo', {'fields':['photo']}),
('Photo', {'fields':['display_photo']}),
]
list_display = ['title', 'height', 'weight', 'color']
readonly_fields = ('display_photo',)
admin.site.register(Product, ProductAdmin)
And finally - MEDIA_ROOT and MEDIA_URL - in my case they should be:
MEDIA_ROOT = '/home/nervosa/DjangoProjects/Sit_test/'
MEDIA_URL = '/uploads/'
Now image is displayed properly after uploading. Thanks for attention and answers.