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="..." />
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)
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,
I did break my head to implement django-hitcount on my blog.
I could do the views count works, but are happening an error to access in my administration page.
Following the code and the error image:
Thank you.
urls.py
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
from blog.views import index, blog, post
urlpatterns = [
path('admin/', admin.site.urls),
path('', index, name='home'),
path('blog/', blog, name='post-list'),
path('post/<id>/', post, name='post-detail'),
path('ckeditor', include('ckeditor_uploader.urls')),
path('hitcount/', include(('hitcount.urls', 'hitcount'), namespace='hitcount')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
from django.shortcuts import render, get_object_or_404, redirect, reverse
from .models import Post, Author
from django.db.models.aggregates import Count
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from hitcount.models import HitCount
from hitcount.views import HitCountMixin
...
def post(request, id):
category_count = get_category_count()
most_recent = Post.objects.order_by('-timestamp')[:3]
popular_posts = Post.objects.order_by('-hit_count_generic__hits')[:3]
post = get_object_or_404(Post, id=id)
hit_count = HitCount.objects.get_for_object(post)
hit_count_response = HitCountMixin.hit_count(request, hit_count)
count_hit = True
if request.method == "POST":
return redirect(reverse("post-detail", kwargs={
'id': post.pk
}))
context = {
'post': post,
'hit_count': hit_count,
'category_count': category_count,
'popular_posts': popular_posts,
'views': Post.objects.get(pk=1),
# views.hit_count.hits
# views.hit_count.hits_in_last(days=7)
}
return render(request, 'blog/post.html', context)
post.html
{% extends 'blog/base.html' %}
{% load static %}
{% load hitcount_tags %}
{% block content %}
<body>
<div class="container">
<div class="row">
<div class="col-md-8">
<div>
<div class="" >
<div class="card mb-3">
<img src="{{ post.thumbnail.url }}" class="card-img-top with:"100%"" alt="...">
<div class="card-body">
<h5 class="card-title">{{ post.title }}</h5>
<img src="{{ post.author.profile_picture.url}}" alt="..." class="rounded-circle width="40" height="40"" >
<p>{{ post.author }} | <i class="far fa-clock"></i> {{ post.timestamp|timesince }} ago | <i class="far fa-eye"> {% get_hit_count for post %} views</i></p>
<div>
<hr class="my-4">
<p class="card-text">{{ post.content|safe }}</p>
</div>
<p class="card-text"><small class="text-muted">{{ post.timestamp}}</small></p>
</div>
</div>
</div>
</div>
</div>
<!--Side Bar-->
{% include 'blog/sidebar.html' with most_recent=most_recent category_count=category_count %}
</div>
</div>
</body>
http://127.0.0.1:8000/admin/hitcount/hitcount/
enter image description here
Can you share your admin.py related this model? Because I had the same problem and fixed it in admin.py.
How I fixed my problem in my admin.py file:
class PostAdmin(admin.ModelAdmin):
list_display = ('id', 'baslik', 'kategori', 'slug', 'taslakDurumu', 'formatted_hit_count')
def formatted_hit_count(self, obj):
return obj.current_hit_count if obj.current_hit_count > 0 else '-'
formatted_hit_count.admin_order_field = 'hit_count'
formatted_hit_count.short_description = 'Hits'
it was like this and appered same error so I've added () and worked.
Like this:
def formatted_hit_count(self, obj):
return obj.current_hit_count() if obj.current_hit_count() > 0 else '-'
formatted_hit_count.admin_order_field = 'hit_count'
formatted_hit_count.short_description = 'Hits'
admin.site.register(Post, PostAdmin)
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)