I have tried everything but somehow i cannot see images uploaded by user.I have deployed code on heroku and every static file is getting loaded properly. User is even going to correct path of image but somehow server is showing errors of not finding image.
Settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
#STATICFILES_DIRS = (
# os.path.join(PROJECT_ROOT, 'static'),
#)
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Models.py
#this is for photos upload by user
class You(models.Model):
user = models.ForeignKey(User,null=True)
name=models.CharField(max_length=30,blank=True,default='pictures/videos')
docfile = models.FileField(upload_to='documents/%Y/%m/%d', null=True,blank=True)
def __unicode__(self):
return self.user.username
#Views.py(To upload files)
#login_required
def upload(request):
if request.method == 'POST':
newdoc = You(docfile = request.FILES['file'],user=request.user)
newdoc.save()
msg='dee'
# Redirect to the document list after POST
return HttpResponse(json.dumps({'message': msg}))
else:
form = DocumentForm()
# Render list page with the documents and the form
return render(request,'mat_upload.html',{'form':form})
Template(gallery.html)
{% for document in documents %}
<img class="img-responsive" src="{{MEDIA_URL}}/media/{{ document.docfile }}" alt="hiiii" style="max-width: 100%;
height: 250px;" />
{% endfor %}
#login_required
def gallery(request):
documents = You.objects.filter(user=request.user)
return render(request,'gallery.html',{'documents': documents,})
Urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic import RedirectView
admin.autodiscover()
import harpoons.views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('harp.urls')),
url(r'^password_reset_recover/', include('password_reset.urls')),
url(r'^accounts/', include('allauth.urls')),
]
You cannot save user-uploaded files locally on Heroku. The filesystem is ephemeral, and does not persist across dyno restarts or between concurrent dynos. You need to upload them somewhere more permanent; a popular choice is Amazon S3, and there are plenty of libraries that will do that for you.
Related
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'),
)
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 have followed many of the answers provided here but I still cannot open the file.
I have an text file that I would like to render on my home.html. I rewrote my views.py as suggested:
def homepage_view(request):
module_dir = os.path.dirname(__file__)
file_path = os.path.join(module_dir, 'my_text.txt')
data_file = open(file_path, 'r')
data = data_file.read()
context = {'intro' : data}
return render(request, 'home.html', context)
Here is my home.html. The html includes: from . import forms, from . import views:
<div class="intro">
{% block intro %}
{{block.super }}
{{intro}}
{% endblock %}
</div>
My app/urls.py is:
from page import views
app_name = 'page'
urlpatterns = [
path('home/', views.homepage_view, name='homepage_view'),
path('upload/', views.csvUpload, name='csv_upload'),
path('zip/', views.zipUser_view, name = 'zipUser_view'),
path('results/', views.results_view, name='results_view'),
path('ky_outline/', views.display_ky_image, name = 'ky_image'),
]
My structure is:
myproject/
__pycache__
__init__.py
settings.py
urls.py
wsgi.py
my/app ('page')
__pycache__
migrations
static
page
css
style.css
images
media
my_text.txt
static and media settings are:
STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = [],
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
What am I missing or have I looked at this too long?
In views, try to put the path manually instead of use os, if it's work then is problem of how you give the path to open()
Running django 2.0 in development and I am trying to display user uploaded images in a List view.
Here is the line for the img tag
<img class="img-responsive" src="{{MEDIA_URL }}{{ selected_membership.image }}" alt="Subscription Logo">
For testing purposes {{ MEDIA_URL }}{{ selected_membership.image }} returns "my_image.jpg". So clearly the MEDIA_URL is not working, but the second part is.
Urls.py
...
if settings.DEBUG:
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Serve static and media files from development server
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Settings.py
...
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(PROJECT_DIR)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
{{ MEDIA_URL }} Needs to return /media/
django model (ImageField) support calling url for your image. You don't have to use MEDIA_URL. Just using {{ selected_membership.image.url }} instead.
It will give your image path and name.
Django does not provide MEDIA_URL keyword to templates. It uses in models for serve files that saved through the model field such as FileField or ImageField. If you sure that you need MEDIA_URL keyword in your templates you can implement it as context variable. For example:
class ExampleView(TemplateView):
template_name = 'example/template.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['MEDIA_URL'] = 'your_media_url'
return context
If you need this url for model field's file you can simply write in your template something like:
{{ model_name.field_name.url }}