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)
Related
I'm currently using UpdateView to add edit functionality to my Django project. It's working correctly insofar as I can edit my data, however when I submit the new data, it returns a NoReverseMatch error:
NoReverseMatch at /MyHealth/edit/8
Reverse for 'health_hub_history' not found. 'health_hub_history' is not a valid view function or pattern name.
I've researched it and added a get_absolute_url to my model, but it isn't working. Any help would be appreciated!
models.py:
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
class HealthStats(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(auto_now=True)
weight = models.DecimalField(max_digits=5, decimal_places=2)
run_distance = models.IntegerField(default=5)
run_time = models.TimeField()
class Meta:
db_table = 'health_stats'
ordering = ['-date']
def get_absolute_url(self):
return reverse('health_hub_history')
def __str__(self):
return f"{self.user} | {self.date}"
urls.py:
from django.urls import path
from django.contrib.staticfiles.storage import staticfiles_storage
from django.views.generic.base import RedirectView
from . import views
app_name = 'HealthHub'
urlpatterns = [
path('', views.home, name='home'),
path('MyHealth/', views.health_hub, name='health_hub'),
path('MyHealth/update', views.UpdateHealth.as_view(), name='health_hub_update'),
path('MyHealth/history', views.health_history, name='health_hub_history'),
path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))),
path('MyHealth/delete/<item_id>', views.delete_entry, name='health_hub_delete'),
path('MyHealth/edit/<int:pk>', views.EditHealth.as_view(), name='health_hub_edit'),
]
Views.py:
class EditHealth(UpdateView):
model = HealthStats
template_name = 'health_hub_edit.html'
fields = ['weight', 'run_distance', 'run_time']
health_hub_edit.html:
{% extends 'base.html' %}
{% load static %}
{%load crispy_forms_tags %}
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 text-center">
<h1>Edit my Data</h1>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-auto text-center p-3">
<form method="post" style="margin-top: 1.3em;">
{{ form | crispy }}
{% csrf_token %}
<button type="submit" class="btn btn-signup btn-lg">Submit</button>
</form>
</div>
</div>
<div class="row justify-content-center">
</div>
</div>
{% endblock content %}
This error occurs because the django couldn't resolve the url
you didn't specify a primary key to base the query on.
you should modify this function
def get_absolute_url(self):
return reverse('health_hub_history', kwargs={'user': self.user})
also that health_history url is it a class based view you should add .as_view() to the end and observe camel casing
Lastly your url should observe the primary key specified
You can do this:
class EditHealth(UpdateView):
model = HealthStats
template_name = 'health_hub_edit.html'
fields = ['weight', 'run_distance', 'run_time']
def get(self, request):
return HttpResponse("health_hub")
def post(self, request):
# do something
return redirect("health_hub")
urlpatterns = patterns('',
url('', views.home, name='home'),
url('MyHealth/', views.health_hub, name='health_hub'),
url('^MyHealth/update', views.UpdateHealth.as_view(), name='health_hub_update'),
url('MyHealth/history', views.health_history, name='health_hub_history'),
url('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))),
url('MyHealth/delete/<item_id>', views.delete_entry, name='health_hub_delete'),
url('MyHealth/edit/<int:pk>', views.EditHealth.as_view(), name='health_hub_edit'),
)
This will solve your problem
I found the answer to this issue here:
https://stackoverflow.com/a/48068932/19053957
Looks like all I need to do was refer to the app name prior to the name of the URL in get_absolute_url()!
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,
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="..." />
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)