I am new to Django, and I am doing a simple web application that saves and displays products. But my problem is when I tried to display the product information I could display everything except the product image. You can see my code below.
settings.py in the static section:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
The main urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('pages.urls')),
path('products/',include('products.urls')),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
The models.py of the Products application:
from django.db import models
from django.db.models.deletion import CASCADE
from django.db.models.fields import CharField, DateField, DateTimeField
from datetime import datetime
from django.db.models.fields.related import ForeignKey, ManyToManyField
# Create your models here.
class Product(models.Model):
categories = [
('Phone', 'Phone'),
('Computer', 'Computer'),
]
name = models.CharField(max_length = 50, default='Nothing', verbose_name='title')
content = models.TextField(default='Empty', null = True, blank = True, verbose_name='description')
price = models.DecimalField(max_digits = 5, decimal_places = 2, default=0.0)
image = models.ImageField(upload_to = 'photos/%y/%m/%d', default='media/photos/default/default_product.png',
verbose_name='picture')
active = models.BooleanField(default = True)
category = models.CharField(max_length=50, null=True, choices=categories)
def __str__(self):
return self.name
class Meta:
#verbose_name = 'name'
ordering = ['-name']
And finally in the products.html:
{% block content %}
{% comment "" %}{{pro}}{% endcomment %}
{% for product in pro %}
<h1>{{product.name}}</h1>
<h1>{{product.content}}</h1>
<h1>{{product.price}}</h1>
</img src="{{product.image}}" alt="">
<h1>-----------------------------------</h1>
{% endfor %}
{% endblock content %}
try this.Note that to get image you have to access the .url
{% block content %}
{% comment "" %}{{pro}}{% endcomment %}
{% for product in pro %}
<h1>{{product.name}}</h1>
<h1>{{product.content}}</h1>
<h1>{{product.price}}</h1>
<img src="{{ product.image.url }}" alt=""/>
<h1>-----------------------------------</h1>
{% endfor %}
{% endblock content %}
Related
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 having issues serving images based on the ImageField in Django.
models.py part looks like that:
class Post(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
category = models.ManyToManyField(Category)
trip = models.ForeignKey(Trip, on_delete=models.CASCADE)
main_image = models.ForeignKey(Image, on_delete=models.CASCADE, related_name='main_image')
images = models.ManyToManyField(Image, related_name='images')
class Image(models.Model):
name = models.CharField(max_length=32)
picture = models.ImageField(upload_to='pictures/', blank=True)
trip = models.ForeignKey(Trip, on_delete=models.CASCADE)
taken = models.DateTimeField(blank=True, null=True)
uploaded = models.DateTimeField(default=timezone.now)
def __unicode__(self):
return self.name
settings.py contains the MEDIA_URL and MEDIA_ROOT:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Also included what I've found in other SO topics in the urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.contrib.staticfiles.urls import static, staticfiles_urlpatterns
from django.conf import settings
from markdownx import urls as markdownx
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
url(r'^markdownx/', include('markdownx.urls')),
] + staticfiles_urlpatterns() + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In the end I put it in the html template like that:
{% extends 'blog/base.html' %}
{% block leftcolumn %}
{% for post in posts %}
<div class="leftcolumn">
<div class="card" style="max-width: 100%">
<h2>{{ post.title }}</h2>
<h5>published: {{ post.published_date }}, by: {{ post.author }}</h5>
<div><img src="{{ post.main_image.url }}"></div>
<p>{{ post.byline }}</p>
</div>
</div>
{% endfor %}
{% endblock %}
But the image is not shown..
I can see the image if I go to the url host:8000/media/pictures/test_photo.jpgand in general I can display images on the page (e.g. within django-markdownx field) but not through ImageField url.
Any ideas what's wrong here?
This line:
<div><img src="{{ post.main_image.url }}"></div>
should be:
<div><img src="{{ post.main_image.picture.url }}"></div>
The reason is your model Image does not have an url method. The method belongs to the ImageField, in this case picture.
In Models.py,
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length= 100)
pub_date = models.DateTimeField('Date Is Published')
image = models.ImageField(upload_to="Question_Image", blank=True)
def __str__(self):
return self.question_text
class Choice(models.Model):
choice_text = models.CharField(max_length= 200)
votes = models.IntegerField(default= 0)
question = models.ForeignKey(Question, on_delete= models.CASCADE)
def __str__(self):
return self.choice_text
In settings.py, i added
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mysite/media')
In mysite/urls.py,
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^polls/', include('polls.urls', namespace= "polls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In index.html,
{% extends 'polls/base.html' %}
{% block main_content %}
{% if latest_questions %}
<ul>
{% for question in latest_questions %}
<li><a href={% url 'polls:detail' question.id %}>
<b>{{question.question_text}}</b>
<img src="{{question.question_text.image.url}}">
</a>
</li>
{% endfor %}
</ul>
{% else %}
<p> You have no questions. Please add some.</p>
{% endif %}
{% endblock %}
but there seems to be no uploading of image which was what i wanted to add to poll app created from 'my first django app' videos on youtube.
Please help.
Change this from:
<img src="{{question.question_text.image.url}}">
To the following one:
<img src="{{question.image.url}}">
I'am begginer in Django so please try to understand me.
I have a problem with the blocks in my django project. I created the base.html like this
{% include 'firmy/header.html' %}
<html>
<body>
<h4>Ostatnio dodane</h4>
{% block firmy %}
{% endblock %}
<h4>Kategorie</h4>
{% block kategorie %}
{% endblock %}
</body>
{% include 'firmy/footer.html' %}
</html>
and {%block firmy%} showing me every records what I want from another file but the {%block kategorie%} showing nothing.
in views.py I have the code:
from django.shortcuts import render
from .models import Witryna, Kategorie
from django.utils import timezone
def widok_strony(request):
firmy = Witryna.objects.filter(data_publikacji__lte=timezone.now()).order_by('data_publikacji')
return render(request, 'firmy/widok_strony.html', {'firmy': firmy})
def widok_kategorii(request):
kategorie = Kategorie.objects.all().order_by('glowna')
return render(request, 'firmy/widok_kategorii.html', {'kategorie': kategorie})
and in urls.py i have the code :
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.widok_strony, name='widok_strony'),
url(r'^$', views.widok_kategorii, name='widok_kategorii'),
]
and on the end models.py
from django.db import models
from django.utils import timezone
class Kategorie(models.Model):
glowna = models.CharField(max_length=150, verbose_name='Kategoria')
class Meta:
verbose_name='Kategoria'
verbose_name_plural='Kategorie'
def __str__(self):
return self.glowna
class Witryna(models.Model):
nazwa = models.CharField(default="", max_length=150, verbose_name = 'Nazwa strony')
adres_www = models.CharField(max_length=70, verbose_name='Adres www')
slug = models.SlugField(max_length=250, verbose_name='Przyjazny adres url')
email = models.CharField(max_length=100, verbose_name='Adres e-mail')
text = models.TextField(max_length=3000, verbose_name='Opis strony')
kategoria = models.ForeignKey(Kategorie, verbose_name='Kategoria')
data_publikacji = models.DateTimeField(blank=True, null=True, verbose_name='Data publikacji')
class Meta:
verbose_name='Strona www'
verbose_name_plural = 'Strony www'
def publikacja(self):
self.data_publikacji=timezone.now()
self.save()
def __str__(self):
return self.nazwa
and widok_kategorii.html
{% extends 'firmy/base.html' %}
{% block kategorie %}
{% for kategoria in kategorie %}
<p>{{ kategoria.glowna }}</p>
{% endfor %}
{% endblock kategorie %}
Really I don't know where is the problem but when I open the browser on localhost:8000 the I can't see the details from class Kategorie.
You have a huge misconception about how views and URLs work.
A URL can only be served by one view. That view will be entirely responsible for creating the response, which it usually does by rendering a single template. You need to pass all the information for your template from that view.
I hope you can help me withmy Django project. I am able to upload an images under a media_cdn folder, inside a folder based on the name of the slug. The problem occurs when I try to display the image inside my post list and post.
Can you please have a look at my code and offer a solution. I spent hours trying to get it to work. Please help.
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn/')
models.py
def upload_location(instance, filename):
return "%s/%s" %(instance.slug, filename)
class Post(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique=True)
image = models.ImageField(upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
body = models.TextField()
date = models.DateTimeField()
updated = models.DateTimeField(auto_now=True)
postlist.html
{% block content %}
{% for post in posts %}
<div class="container w3-card-4">
{% if post.image %}
<img src="{{ post.instance.image.url }}">
{% endif %}
...
post.html
{% block content %}
<div class="row">
<div class="container w3-card-4">
{% if instance.image %}
<img src= "{{ instance.image.url }}" class="img-responsive">
{% endif %}
...
url.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('personal.urls')),
url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I don't know what else to try to call that image from the folder. Any advice would be greatly appreciated. Thank you!
Use post.image.url instead of post.instance.image.url. Check the documentation.
ImageField inherits all the attributes of the FileField which includes url.