Not showing image on upload, what is the problem?
setting.py
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = 'media/'
html.
{% for tt in article %}
<div class="content_box">
<div class="content_l left">
<div class="horoscope_box_big">
<div class="blog_img1">
<img src="{{ tt.image.url }}" alt="{{tt.title}}" width="50%" /> {{ tt.image.url }}
</div>
<h1 class="blog_title1"> {{ tt.Title }}
<div class="blog_descr1"><h1>more about</h1>
<p> {{ tt.body }}</p>
</div>
</div>
{% endfor %}
models.py
class Blogmodel(models.Model):
Title = models.TextField(blank=True, null=True)
image = models.ImageField(upload_to="images/",null=True)
body = RichTextField(blank=True, null=True)
slug = AutoSlugField(populate_from='Title', unique=True,blank=True, null=True)
def __str__(self):
return self.Title
views.py
def blog_list(request):
articles = Blogmodel.objects.all()
args = {'articles':articles}
return render(request,'blog.html',args)
def blogDetail(request, slug):
article = Blogmodel.objects.filter(slug=slug)
args = {'article':article}
return render(request,'blogdetail.html',args)
urls.py
from django.urls import path
from .views import singCategory,Home,blog_list,blogDetail
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('',Home,name= "Home"),
path('horoscope/<slug:slug>/<slug:cat>',singCategory,name='singCategory'),
path("blog/",blog_list, name="blog_list"),
path("blog/<slug:slug>",blogDetail, name="blogDetail"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your settings.py:
MEDIA_URL = '/media/'
Your template:
<img src="{{ article.image.url }}">
check if you have Pillow installed, pip install pillow,
Related
I'm trying to get images for an object filtered by the object's id, but for now, I don't even see any request to it in my MySQL database. The snippets of my code are below.
models.py:
class Media(models.Model):
word = models.ForeignKey(Word, on_delete=models.CASCADE)
title = models.TextField(max_length=100, null=True)
image = models.ImageField(upload_to='images/')
views.py:
class MediaListView(generic.ListView):
model = Media
template_name = 'dictionaty_web/index.html'
context_object_name = 'images'
def get_queryset(self):
return Media.objects.filter(word=self.request.resolver_match.kwargs['pk'])
urls.py:
urlpatterns = [
path('languages/<int:pk>/', views.WordMapListView.as_view(), name='wordmaps'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
index.html:
{% for word in words %}
<div class="col-sm text-center">
<div class="card" style="width: 18rem;">
<img scr="{{ MEDIA_URL }}{{ image.image.url }}">
<div class="card-body">
<h5 class="card-title">{{ word.value }}</h5>
</div>
</div>
</div>
{% endfor %}
Your urls.py is also important when serving images in django.
do you have imported in your urls.py the following code
from django.conf import settings
from django.conf.urls.static import static
urlpatterns=[
path('url/', name_of_view, name = 'url_name'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Here is my settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Here is 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('laxmi.urls')),
] + static(settings.MEDIA_URL, documents_root=settings.MEDIA_ROOT)
Here is my model:
class Services(models.Model):
title = models.CharField(max_length=250)
desc = models.TextField()
img = models.ImageField(upload_to='img')
def __str__(self):
return self.title
Views:
def index(request):
why_choose_uss = why_choose_us.objects.all()
servicess = Services.objects.all()
return render(request, 'laxmi/index.html', {'servicess': servicess, 'why_choose_uss':
why_choose_uss})
Template:
{% for services in servicess %}
<div class="col mb-4">
<div class="card">
<img src="{{services.img.url}}"class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{services.title}}</h5>
<p class="card-text">{{services.desc}}</p>
Lern More
</div>
</div>
</div>
{% endfor %}
And here is an image upload from admin pannel but its not shwoing in template
here it is model in admin panel
output in template
Try to substitute
<img src="{{services.img.url}}"class="card-img-top" alt="...">
with
<img src="{{services.img.url}}" class="card-img-top" alt="..." />
I want to show the topic title in the website template url link on django 3.
currently opening the topic id number.
for example : http://localhost:8000/detay/4
for example : http://localhost:8000/detay/2
for example : http://localhost:8000/detay/1
but I want to do it this way
for example : http://localhost:8000/detay/1/this-is-topic-title
or
for example : http://localhost:8000/detay/3/this-is-topic-title
.
.
.
views.py
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import *
# Create your views here.
def index(request):
girdiler = Deneme1Model.objects.filter(yuklemeTarihi__lte=timezone.now()).order_by('-yuklemeTarihi')
context ={
'girdiler':girdiler
}
return render(request, 'deneme1Uygulama/index.html', context)
def ekle(request):
return render(request, 'deneme1Uygulama/ekle.html')
def detay(request, pk):
girdiler = Deneme1Model.objects.filter(pk=pk)
context ={
'girdiler':girdiler
}
return render(request, 'deneme1Uygulama/detay.html', context)
def sayfaYok(request):
return render(request, 'deneme1Uygulama/404.html')
urls.py
from django.urls import path
from .import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.index, name='index'),
path('ekle/', views.ekle, name='ekle'),
path('detay/<int:pk>', views.detay, name='detay'),
path('404/', views.sayfaYok, name='sayfaYok'),
]
urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
from django.db import models
from django.utils import timezone
# Create your models here.
class Deneme1Model (models.Model):
baslik = models.CharField(max_length=50, verbose_name='BAŞLIK')
aKaydi = models.CharField(max_length=50, verbose_name='A KAYDI')
dosyaYukle = models.FileField(upload_to='media', verbose_name='DOSYA YÜKLE')
yuklemeTarihi =models.DateTimeField(default =timezone.now)
yayinKontrol = models.BooleanField(default=True)
def __str__(self):
return self.baslik
detay.html
{% block content %}
<div class="row">
{% if girdiler %}
{% for girdi in girdiler %}
<div class="col-12 d-flex justify-content-center">
<div class="card w-100">
<img class="card-img-top img-fluid umaxhe20" src=" {{ girdi.dosyaYukle.url }} " alt="Card image cap">
<div class="card-body">
<h5 class="card-title"> {{ girdi.baslik }} </h5>
<p class="card-text"> {{ girdi.aKaydi }} </p>
{{ girdi.yuklemeTarihi }}
</div>
</div>
</div>
{% endfor %}
{% else %}
{% url 'sayfaYok' %}
{% endif %}
</div>
{% endblock content %}
Not tested but probably something like this
urls.py
urlpatterns = [
path('detay/<int:pk>', views.detay, name='detay'),
path('detay/<int:pk>/<string:topic>', views.detay_topic, name='detay-topic'),
]
views.py
def detay_topic(request, pk, topic):
...
How can I display images from django models on tis page datat.ru/shop ?
I the source page code see <img class='img-fluid w-100' src="/media/images/2.png" alt="img" />
But only http://datat.ru/static/media/images/2.png returns image
How can I convert src="{{ shop.cover.url }}" to static/media/images/ ???
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
path('shop/', views.shop_list, name='shop'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
]
models.py
from django.conf import settings
from django.db import models
from django.utils import timezone
class Company(models.Model):
title = models.TextField()
cover = models.ImageField(upload_to='images/')
def __str__(self):
return self.title
shop_list.html
{% extends 'blog/base.html' %}
{% load staticfiles%}
{% block content %}
{% for shop in shops %}
<div class="container">
<div class="row">
<img class='img-fluid w-100' src="{{ shop.cover.url }}" alt="img" />
</div>
</div>
{% endfor %}
<!-- <img class="scale-with-grid" src="{{ shop.cover.url }}"/> -->
{% endblock %}
add this to settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/
and this to urls
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I'm learning django, and I have a problem, I'm doing a virtual store and when I click on add a product to the shopping cart you should redirect me to another page, but can not find it, this is my code and my error:
django.template.exceptions.TemplateDoesNotExist: productos/carritocompras_form.html
detalle.html
<div class="fixed-action-btn" style="bottom:90px;">
<form action="{% url 'aniadir_carrito' %}" method="post">
{% csrf_token %}
<input type="hidden" name="usuario" value="{{request.user.pk}}">
<input type="hidden" name="produto" value="{{object.pk}}">
<input type="hidden" name="precio" value="{{object.precio}}">
<button class="btn-floating btn-large red pulse">
<i class="large material-icons">add_shopping_cart</i>
</button>
</form>
</div>
<div class="fixed-action-btn">
<a class="btn-floating btn-large red pulse">
<i class="large material-icons">add_shopping_cart</i>
</a>
<ul>
</ul>
</div>
url.py
from django.conf import settings
from django.urls import include, path
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
from tienda.users.views import (
Indice, ListarProductos, DetalleProducto, ComentarioProducto, Ingresar, Salir, CambiarPerfil,
CarritoCompras, AniadirCarrito, ListarCarrito, ListarCarritoPendientes, ListarCarritoFinalizadas, EliminarCarrito
)
urlpatterns = [
path('', Indice.as_view(), name="indice"),
path("listado_productos", ListarProductos.as_view(), name="listado_productos"),
path("detalle_producto/<int:pk>/", DetalleProducto.as_view(), name="detalle_producto"),
path("crear_comentario/", ComentarioProducto.as_view(), name="crear_comentario"),
path("ingresar/", Ingresar.as_view(), name="ingresar"),
path("salir/", Salir.as_view(), name="salir"),
path("editar_perfil/", CambiarPerfil.as_view(), name="editar_perfil"),
path("aniadir_carrito", AniadirCarrito.as_view(), name="aniadir_carrito"),
path("listar_carrito", ListarCarrito.as_view(), name="listar_carrito"),
path("listar_pendientes", ListarCarritoPendientes.as_view(), name="listar_pendientes"),
path("listar_finalizado", ListarCarritoFinalizadas.as_view(), name="listar_finalizado"),
path("eliminar_carrito", EliminarCarrito.as_view(), name="eliminar_carrito"),
# Django Admin, use {% url 'admin:index' %}
path(settings.ADMIN_URL, admin.site.urls),
# Your stuff: custom urls includes go here
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
class AniadirCarrito(LoginRequiredMixin, CreateView):
model = CarritoCompras
fields = ('usuario','producto', 'precio',)
success_url = reverse_lazy('indice')
login_url = 'ingresar'
models.py
class CarritoCompras(models.Model):
producto = models.ForeignKey(Producto, related_name="producto_carrito", on_delete=models.CASCADE)
usuario = models.ForeignKey(get_user_model(), related_name="carrito_usuario", on_delete=models.CASCADE)
precio = models.IntegerField()
direccion = models.CharField(max_length=300)
datos_payu = models.CharField(max_length=600)
comprado = models.BooleanField(default=False)
pendiente = models.BooleanField(default=False)
def __str__(self):
return "{} {}".format(self.usuario)