If I put my image in /media/ folder, it doesn't works. But if I put them in '/static/' folder it works.
{% extends 'base.html' %}
{% block contain %}
<h1>New Report</h1>
<form id="create" method="POST" action="" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Confirm">
</form>
{% for report in reports %}
<P> {{report.title}} </P> <br>
<img src="{{STATIC_URL}}<name of the image>" width='100px' height='100px'> =====> I can see the image
<img src="{{MEDIA_URL}} <name of the image>" width='100px' height='100px'> =====> I cant see the image
<img src="/static/<name of the image>" width='100px' height='100px'> =====> I cant see the image
<img src="/media/<name of the image>" width='100px' height='100px'> ====>>>> I cant see the image
{% endfor %}
{% endblock %}
Are you sure django testing server (or apache/nginx) knows about your media folder?
Try to add this to urls.py (in case you're using development server):
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
Putting images in your static folder will work, as the files in the static folder are served on the site. This is a potential solution and this discussion seems to suggest it's reasonable for some images. On my site the images in the media folder are located at /uploads/<name of the image>. This is what MEDIA_URL is set to. However I never explicitly call MEDIA_URL as all my images are tied into models so django handles that for me. My guess would be double check the name of the folder you're storing the images in and make sure you're looking at the right place. Second I would make sure that {{MEDIA_URL}} isn't undefined in the template.
Related
I'm learning Django using W. Vincent's "Django for beginners". I got to the part where we have to customize the password change page (p. 186). According to the author:
"Django already has created the views and URLs for us, we only need to
change the templates."
I created a new template password_change_form.html but when I start a local server and go to the localhost/accounts/password_change, I still see the old default page with the "Django Administration" header. Here is the code:
{% extends "base.html" %}
{% block title %}Password Change{% endblock title %}
{% block content %}
<h1>Password change</h1>
<p>Please enter your old password, for security's sake, and then enter your new password twice so we can verify you typed it in correctly.</p>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input class="btn btn-success" type="submit" value="Change my password">
</form>
{% endblock content %}
I'm surprised because everything worked well up until this point, as I was able to successfully updated the login and signup pages' templates. What do you think might be going wrong? Thanks.
This is happening because in "Django For Beginners" book, the author does not configure static file setting in the settings.py file the css you are seeing in the template is because of bootstrap's cdn.
If you want to clear that problem you have to configure static files settings in settings.py.
This article by the same author can be helpful for you
I'm looking to display an uploaded .html file in an iFrame on my template. I would rather NOT set it up as a url to visit in the urls.py file, I upload .html files from the admin panel to the media folder like so:
model
# Portfolio project overview model
class Work(models.Model):
html = models.FileField(upload_to="work_app/media/htmls/", null=True, blank=True)
settings.py
MEDIA_ROOT = str(BASE_DIR) + "/media/"
MEDIA_URL = '/media/'
STATIC_ROOT = str(BASE_DIR) + "/static/"
STATIC_URL = '/static/'
urls.py
urlpatterns = [
include("personal_portfolio_project.apps.resume_app.urls")),
path("work/", include("personal_portfolio_project.apps.work_app.urls")),
]
if DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My first attempt to display it using this template.html code:
{% extends "base.html" %}
{% load static %}
{% block page_content %}
<h1>{{ work.title }}</h1>
<div class="row">
<div class="col-md-8">
{% if work.html %}
<iframe height="100%" width="100%" src="{{ 'work.html.url' }}">
</iframe>
{% endif %}
</div>
</div>
{% endblock %}
...looks like this:
As you can see, the iFrame is displaying, but seems like it can't find the .html file (404).
I saw in a few other posts that the html line should be:
<iframe height="100%" width="100%" src="{% url 'work.html' %}"> </iframe>
..and to also add X_FRAME_OPTIONS = 'SAMEORIGIN' to your settings.py file, so I did both those, where I now get:
What is this trying to tell me? What am I missing?
UPDATE
I have also tried:
<iframe height="100%" width="100%" src="{{ work.html }}"> </iframe>
to which I get another 404:
UPDATE
The closest I've gotten is using this:
<iframe type="html" height="100%" width="100%" src="{{ work.html.url }}"> </iframe>
But it gives me this screen:
I put the url above the image to make sure that it is in fact correct. According to other answers, they said just to enable X_FRAME_OPTIONS = 'SAMEORIGIN' and it'll work, but it doesn't for me. Any help from here would be greatly appreciated. Thanks!
I take back my last UPDATE above, what I had to do was clear my cache, or run the page in incognito mode as none of my changes were being reflected on the page due to the cache. Once I did that, it started showing the iframe properly.
Another option I was exploring was to set an xframe exemption decorator to the view that handles rendering the post details page, which would look something like:
from django.shortcuts import render
from django.views.decorators.clickjacking import xframe_options_exempt
# Create your views here.
from .models import Work
#xframe_options_exempt
def work_detail(request, pk):
work = Work.objects.get(pk=pk)
context = {
'work': work
}
return render(request, 'work_detail.html', context)
which also seemed to work, but I'm reverting back to the SAMEORIGIN method.
I've read through a few answers/articles at these links, but am still confused as all of them SEEM to be slightly different than what I'm after:
here
here
here
here
here
I am looking to make use of Django's ImageField function for uploading images from my admin page, to my portfolio/blog's app space. My folder structure looks like this:
Portfolio_Blog_Website
|---personal_portfolio_project
|---projects_app
|---migrations
|---static
|---img
|---templates
So I want to upload images to/display on the template from, the app > static > img folder.
Currently, I have STATIC_URL = 'static/' set, and I'm manually drag and dropping image files into that folder, and using models.FilePathField(path="/img") in the model, and displaying them (in a for loop) with <img src="{% static project.image %}">, which works. I want to switch to be able to upload images from the admin page, and then display them on the app's page like they're supposed to.
From what I've read, we have to define a MEDIA_ROOT and MEDIA_URL variable to use with models.ImageField(upload_to="img/"). The problem I see is that MEDIA_ROOT needs to be an ABSOLUTE path to the folder, which I COULD set as \\C:\Portfolio_Blog_Website\projects_app\static\img, however this isn't necessarily what I want because I'm specifically targeting the one specific app's path, but I don't want to upload images from other app's to that path also, so how can I make this work? I want each app to have its own static > img folders, and then from the admin page, I can upload to those specific app's directories, and then display them on each app's page.
In addition to my folder structure shown above, here's some other details that should help:
personal_portfolio_project > settings.py
STATIC_URL = 'static/'
MEDIA_URL = "/img/" # This doesn't work
MEDIA_ROOT = BASE_DIR # This doesn't work
projects_app > models.py
from django.db import models
# Create your models here.
# Portfolio project overview model
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
# image = models.FilePathField(path="/img") # works as /static/img, this works with STATIC_URL
image = models.ImageField(upload_to="img/") # This doesn't work
projects_app > project_index.html
{% extends "base.html" %}
{% load static %}
{% block page_content %}
<h1>Projects</h1>
<div class="row">
{% for project in projects %}
<div class="col-md-4">
<div class="card mb-2">
<img class="card-img-top" src="{% static project.image %}">
<div class="card-body">
<h5 class="card-title">{{ project.title }}</h5>
<p class="card-text">{{ project.description }}</p>
<a href="{% url 'project_detail' project.pk %}" class="btn btn-primary">
Read More
</a>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
I cant get an image to load in django when i use a for loop, the image will load if i specify the path for each file.
Works:
when I try to use a loop it won't load the images.
view.py:
operators = []
directory =
os.path.join(os.path.join(os.path.join(os.path.join(settings.BASE_DIR)
,'static'),'images'),'operators')
for file in os.listdir(directory):
if file.endswith(".png") or file.endswith(".jpg"):
operators.append(file)
then i try to return image using context.
html file:
{% if operators %}
There are {{ operators|length }} records:
{% for operator in operators %}
<div class="media">
<img src="{{operator}}" class="align-self-center mr-3" alt="...">
</div>
{{operator}}
{% endfor %}
{% else %}
There are no records in the system
{% endif %}
It would be amazing if someone had an idea on how to fix my code.
settings.py:
STATIC_URL = '/static/'
# Pointing django to the static file location.
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
)
The answer may vary depending on which version of Django you're using.
For Django 3.0, the following should work
# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
'static',
]
Then inside templates-
{% load static %}
<img src="{% static '{{ operator.url }}' %}">
I'm guessing the images may appear instead with the following-
<img src="{{ operator.url }}">
I have a Photo model with two fields:
title = models.CharField()
path = models.CharField()
When I adding the new photo in admin panel, the path is equals to /images/image_ex.jpg This is my view file:
def gallery(request):
photos = Photo.objects.all()
return render(request, 'gallery.html', {'photos': photos})
This is the tag in gallery.html:
{% loadstaticfiles %}
<img src="{%static '{{photo.path}}'%}"/>
The problem is that the photo does not render and if I look in the code of the page, the src is equals to something like that:
src="static/%7B%7B%20photo.path%20%7D%7D"
What is the problem? How can I use template variables in src?
P.S. The images folder exists in static folder, the image exists too. I added static directory to settings.py. Also if I change src to a normal one, like
<img src="{static 'images/image_ex.png'%}">
The photo renders normally.
You here pass '{{photo.path}}' as a string to {% static ... %}, hence it will simply prepend the static URL root to this string.
If you want to use the content of photo.path, you can use:
<img src="{% static photo.path %}"/>
So {% static ... %} accepts variables as parameters, and will take the content of the path attribute of the photo variable. (of course given that variable is passed, or is a variable you generate with {% for ... %} loops, etc.
Uses a for tag
{% for p in photos %}
<img src="{% static '{{ p.path }}' %}"/>
{% endfor %}
Better uses Imagefield as field in your model
In your settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Create a folder named “media” in your project (at the same level that your apps)
In your urls.py (main)
from . import views, settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In your models.py
Replace the CharField with Imagefield
image = models.ImageField(upload_to="my_folder_name")
Like this:
class Photo(models.Model):
title = models.CharField()
image = models.ImageField(upload_to="my_folder_name"))
In your views.py
def gallery(request):
photos = Photo.objects.all()
return render(request, 'gallery.html', {'photos': photos})
In your templates
{% for p in photos %}
<img src="{{ p.photo.url }}"/>
{% endfor %}
Do it like this:
<img src="{static 'images/'%}{{image_ex.png}}">
Use it after the static tag scope ends.
For Template
{% for image in all_image %}
<img src="{{ image.image.url }}"/>
{% endfor %}
Solved: load image dynamically in survey.html
"survey.toolsTechnology" is a dynamic variable, every time the
variable changes, the image also changes based on it.
<img src="{% static 'images/'%}{{survey.toolsTechnology}}.png"/>