I have a small problem with django here.
I want to upload a photo of one product in production and want that this photo be shown to me in homepage.
Here is the Product class in models.py:
class Produto(models.Model):
nome = models.CharField(max_length=255, null=False)
foto = models.ImageField(upload_to='mywebsite/staticfiles/static')
def __unicode__(self):
return "%s" % (self.nome)
In my settings.py, I've set these variables:
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'),
)
And in my htm page:
{% for produto in produtos %}
<li>
<div class="col-md-3 biseller-column">
<a href="single.html">
<img src="{{produto.foto.url}}"/>
</a>
<div class="ad-info">
<h5>{{produto.nome}}</h5>
</div>
</div>
</li>
{% endfor %}
</ul>
So, I get my upload and when I upload via web browser the photo appears on staticfiles/static but in not in the site. In web page appears the follow:
Could someone help me?
Thank you a lot.
It looks like you haven't set your media root or added the url configurations hence they're not being served. You can check out how to set these up at the documentation
Problem is in your template.
Try {{ produto.foto.image.url }} instead of {{ produto.foto.url }} to access to image file url.
Related
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 am trying to get the uploaded image to show in the project template. Here is what my code looks like currently:
projects.html
{% extends "base.html" %}
{% block content %}
<h1>{{ project.title }} HELLO</h1>
<div class="content-section">
<div class="media">
<img src="{{ project.image.url }}" alt="beach" width=250px height=250px />
</div>
<div>
<h5>About the project:</h5>
<p>{{ project.description }}</p>
<br>
<h5>Technology used:</h5>
<p>{{ project.tools }}</p>
</div>
</div>
{% endblock content %}
models.py
class Project(models.Model):
title = models.CharField(max_length=500, unique=True)
description = models.TextField(max_length=500)
tools = models.CharField(max_length=200)
image = models.ImageField(default='default.jpg', upload_to="beach_photos", blank=True)
def __str__(self):
return f'{self.title}'
views.py
from django.shortcuts import render
from django.http import HttpResponse
from projects.models import Project
def projects(request):
project = {
'project':Project.objects.all()
}
return render(request, 'projects/projects.html', context = project)
settings.py configuration (app is installed)
STATIC_URL = 'static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
When I inspect the image element in the webpage, the source shows up as
src=""
None of the other calls to the model are appearing either.
Any help would be appreciated.
i think you forgot to add a for-loop in your template. try this:
{% for p in project %}
{{ p.title %}}
{% endfor %}
Make sure that the image field of your record in the database is full.
Access the required model with the python manage.py shell command and check if this model has a value of variable.image.url.
am trying to show pic in django tempate but its not working
here is my settings.py where the path of static and media file
STATIC_URL = '/static/'
STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR , "media")
this is my model.py
the image is store under static/img folder
class Loader_post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Loader")
pick_up_station = models.CharField(max_length=150)
destination_station = models.CharField(max_length=150)
sender_name = models.CharField(max_length=150)
phone_number = PhoneNumberField(null=False, blank=False, unique=True)
receiver_name = models.CharField(max_length=150)
sending_item = models.CharField(max_length=150)
image_of_load = models.ImageField(default='',upload_to='static/img')
weight = models.CharField(max_length=150)
metric_unit = models.CharField(max_length=30, default='')
quantity = models.PositiveIntegerField()
pick_up_time = models.DateField()
drop_time = models.DateField()
paid_by = models.CharField(max_length=150)
created_at = models.DateTimeField(auto_now=True)
published_date = models.DateField(blank=True, null=True)
this is my html template for showing user posted data
{% extends "post.html" %}
{% block content %}
{% load static %}
{% for loader in Loader %}
<h4>Loader Id- {{loader.id}}</h4> Username-{{user.username}}
<h3>Sender name-{{loader.sender_name}}</h3>
</h4>
<p class="card-text">
<h4>pick up station-{{loader.pick_up_station}}</h4>
</p>
<img src="{{ loader.image.url }}" alt="image">
<p class="card-text">{{loader.destination_station}}</p>
<p class="card-text">{{loader.phone_number}}</p>
<p class="card-text">{{loader.receiver_name}}</p>
<p class="card-text">{{loader.sending_item}}</p>
<p class="card-text">{{loader.weight}}</p>
<p class="card-text">{{loader.quantity}}</p>
<p class="card-text">{{loader.pick_up_time}}</p>
<p class="card-text">{{loader.drop_time}}</p>
<p class="card-text">{{loader.paid_by}}</p>
<p class="card-text">{{loader.created_at}}</p>
<a class="btn btn-primary" href="{% url 'Loader:Delete' loader.id %} ">delete</a>
<a class="btn btn-primary" href="{% url 'Loader:Update' loader.id %} ">update</a>
</div> {% endfor %} {% endblock content %}
this is my urls.py
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'Loader'
urlpatterns = [
path('post_detail/', views.Loader_post_view.as_view(), name="post_detail"),
path('post/', views.post.as_view(), name="post"),
path('my_job/', views.Loader_post_list.as_view(), name="my_job"),
path('delete/<int:pk>', views.Loader_post_delete.as_view(), name="Delete"),
path('update/<int:pk>', views.Loader_post_update.as_view(template_name="post_detail.html"), name="Update")
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
how can i remove this error or any bug in my code?
Take a closer look
First of all, you use different names. In the models.py the image attribute corresponds to image_of_load, whereas in your template the src is equal to {{loader.image.url}} not {{loader.image_of_load.url}}. Second, try to put {% load static %} at the very top of your file, which is an advice from the documentation, at least above the {% block content %} tag.
I think that on the models.py file, you should use upload_to='img' because you have set your static folder directory. Remember that the uploaded images by users go to your media folder / URL, not your static folder. The static folder is for CSS files and images that you serve, such as your website's logo.
I hope that helps. Feel free to ask me any more questions!
I'm trying to display an image from a database (SQLite, Django2.7). These images are stored in root/media/pictures.
models.py
class News(models.Model):
news_id = models.AutoField(primary_key=True, editable=False)
news_img = models.FileField(upload_to="pictures/",validators=[FileExtensionValidator(allowed_extensions=['svg'])] )
urls.py
urlpatterns = [...]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
I've try to insert the path in the var in the following methods:
template.html
{% for news_f in news_f%}
<div>
<img src="{{ media }}{{news_f.news_img}}">
</div>
{% endblock %}
and
{% for news_f in news_f%}
<div>
<img src="{{news_f.news_img.url}}">
</div>
{% endblock %}
When I inspect the element in the browser, I get the correct path to the file.
<img src="/media/pictures/file.svg">
But it isn't displayed in the HTML:
Could not load the image
That happens because django doesn't serve static files. Usually you use django along with some webserver like nginx and those servers are more reliable serving files.
Please check out django docs https://docs.djangoproject.com/en/2.2/howto/static-files/deployment/
Your configuration for media files is right, the problem is that Django doesn't serve SVG files with the right mime type by default, this answer explains how to make it work.