Cannot Open Text File To Read Into Django Html - django

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()

Related

got error while setting default image in ImageField Django

my model have an imagefield which stores the image for post . I want to add default image to that in case if not is not uploaded.But I am getting error The 'title_image' attribute has no file associated with it. If I upload image then its working fine.
Models.py
class Post(models.Model):
title_image = models.ImageField(
upload_to='Images/PostTitleImages/',
max_length=None,
default = 'Images/Image_not_found.jpg',
blank = True,
null = True)
home.html
<img src="{{post.title_image.url}}" height="350px"/>
Settings.py
STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static/'),
]
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('MainSite.urls'), name = "Main"),
path('account/',include('account.urls'), name = 'Accounts')
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
what I am doing wrong here I checked the file is in this directory /media/Images/PostTitleImages/
In case of media you need to include the media tag in your template like so:
# template
<img src="{{ media_url }}{{ post.title_image.url }}>
and in your settings add the context processor
# settings.py
'django.template.context_processors.media'

Django : Media Files not displayed in templates

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'),
)

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

Django Media URL not returning string to Media folder

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 }}

Django is not serving media files uploaded by user on heroku

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.