My view isn't rendering any result in the template - django - django

I'm working on a Django project and i'm quite the beginner so i'm really sorry if this is a basic question, my view isn't showing any result in the template,
here's my view:
def all_products(request):
products = Product.objects.all()
context = {'products': products}
return render(request, 'users/home.html', context)
this is the model:
class Product(models.Model):
title = models.CharField(max_length=255)
id = models.AutoField(primary_key=True)
price = models.FloatField(null=True)
picture = models.ImageField(null=True)
category =models.ForeignKey(Category,related_name='products',on_delete=models.SET_NULL,null=True)
developer = models.ForeignKey(Developer, on_delete=models.SET_NULL, null=True)
and finally this is the part of html needed:
<div class="row justify-content-center" >
{% for product in products %}
<div class="col-auto mb-3">
<div class="card mx-0" style="width: 12rem; height:21rem; background-color: black;">
<img class="card-img-top img-fluid" style="width: 12rem; height:16rem;" src="{{ product.picture.url}}" alt="Card image cap">
<div class="card-block">
<h5 class="card-title mt-1 mb-0" style="color:white; font-size: 18px; font-family: 'Segoe UI';"><b>{{product.title}}</b></h5><a href="#">
<p class="card-text text-muted mb-1" style="color:white;">{{product.developer.title}}</p>
<p class="item-price card-text text-muted"><strike >$25.00</strike> <b style="color:white;"> {{product.price}} </b></p>
</div>
</div>
</div>
{% endfor %}
</div>
I also do have some product objects in my database, so where could the problem be?

Try:
<center>
<div class="row justify-content-center" >
{% for product in products %}
<div class="col-auto mb-3">
<div class="card mx-0" style="width: 12rem; height:21rem; background-color: black;">
<img class="card-img-top img-fluid" style="width: 12rem; height:16rem;" src="{{ product.picture.url }}" alt="Card image cap">
<div class="card-block">
<h5 class="card-title mt-1 mb-0" style="color:white; font-size: 18px; font-family: 'Segoe UI';"><b>{{ product.title }}</b></h5><a href="#">
<p class="card-text text-muted mb-1" style="color:red;">{{ product.developer.name }}</p> # Here I putted 'name' but probably you'll put 'title'; depends on model Developer!
<p class="item-price card-text text-muted"><strike>$ 25.00</strike> <b style="color:red;"> ${{ product.price }} </b></p>
</div>
</div>
</div>
<br>
<br>
<br>
<br>
{% endfor %}
</div>
</center>
In the urls.py of the project:
"""teste URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('core.urls')),
]
In the urls.py of the app:
from django.urls import path
from .views import *
urlpatterns = [
path('products/', all_products, name='products')
]
And to show the image I had to install dj_static and put in wsgi.py:
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling, MediaCling
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test.settings')
application = Cling(MediaCling(get_wsgi_application()))

Related

Why I can not display two listviews in one template?

I am working on a Django project where admin can upload a hero banner to the site and can also upload a notification on the home page of the site.
So I made listviews for listing the two HeroListView and NotificationListView for that.
But the second one is not appearing in the page.
Please tell me how to solve this issue.
This is the models.py file
from django.db import models
class Hero(models.Model):
image = models.ImageField(upload_to="heros/")
class Notification(models.Model):
notification = models.CharField(max_length=200)
This is the views.py file.
from django.views.generic import ListView
from .models import Hero, Notification
class HeroListView(ListView):
model = Hero
template_name = "home.html"
context_object_name = "hero_list"
class NoticficationListView(ListView):
model = Notification
template_name = "home.html"
context_object_name = "notification_list"
this is the app/urls.py file
from django.urls import path
from .views import HeroListView, NoticficationListView
urlpatterns = [
path("", HeroListView.as_view(), name="home"),
path("", NoticficationListView.as_view(), name="home"),
]
this is the project/urls.py file
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("heros.urls")),
path("", include("products.urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
{% extends '_base.html' %}
{% block title %}Home{% endblock title %}
{% block content %}
{% load static %}
<div class="container mt-4">
<div id="carouselExampleControls" class="carousel carousel-dark slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="{% static 'images/hero2.jpg' %}" class="d-block w-100" alt="..." style="max-height: 400px;">
</div>
{% for hero in hero_list %}
<div class="carousel-item">
<img src="{{ hero.image.url }}" class="d-block w-100" alt="..." style="max-height: 400px;">
</div>
{% endfor %}
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<div class="div">
{% for note in notification.list %}
<p>{{ note.notification }}</p>
{% endfor %}
</div>
</div>
{% endblock content %}
please tell me how to solve this issue.
You can do it this way
class HeroListView(ListView):
model = Hero
template_name = "home.html"
def get_context_data(self):
context = super(HeroListView, self).get_context_data()
context['hero_list'] = Hero.objects.all()
context['notification_list'] = Notification.objects.all()
return context
You can't access two or multiple views at the same time, so in your case, you can remove NoticficationListView and use only HeroListView to render both hero_list and notification_list

Put a button in the creation of a model

I would like to make sure that in addition to the title, color and description, I would like to make sure that when I create a model it makes me choose which url to render it when Ia person clicks the button. It's possible?
models.py
from django.db import models
from colorfield.fields import ColorField
class Aziende(models.Model):
immagine = models.ImageField()
nome = models.CharField(max_length=250)
prezzo = models.FloatField()
descrizione = models.CharField(max_length=250)
nome_color = ColorField(default='#FF0000')
def __str__(self):
return self.nome
class Meta:
verbose_name_plural = "Aziende"
home.html
[...]
<div class="container">
<div class="row">
{% for Aziende in Borsa %}
<div class="col"><br>
<div class="container text-center">
<div class="card" style="width: 18rem;">
<img src="{{ Aziende.immagine.url }}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="title" style="color: {{Aziende.nome_color}}" >{{Aziende.nome}}</h5>
<p class="card-text">{{Aziende.descrizione}}</p>
<p class="card-text fst-italic text-primary">Valore Attuale: €{{Aziende.prezzo}}</p>
Più info
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
[...]
urls.py (1)
[..]
urlpatterns = [
path('admin/', admin.site.urls),
path('Borsa/', include('Borsa.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('', TemplateView.as_view(template_name='home.html'), name='home'),
]+static(settings.MEDIA_URL, document_root =settings.MEDIA_ROOT)
urls.py (2)
[...]
urlpatterns = [
path('', views.Borsa),
path('Investimenti', views.Investimenti, name='Investimenti'),
]
Thanks in advance!
You can do this way
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
Home
admin
Borsa
Link 3
</div>
</div>

Django media image displays blank box

Hi I'm trying to display an uploaded user image in django but when I try to display it only a blank box appears. However when I click on the image it brings up a new page with the image. I don't know why it isn't displaying on the page.
html
{% load mptt_tags %}
{% recursetree location %}
<div class="card">
<div class="card-body">
<a class="btn btn-primary" type="button" href="/AddClimb/{{node.id}}">Add Climb</a>
</div>
</div>
<img source="{{node.img.url}}" width="500" height="400">
<div class="container">
<div class="row equal">
<div class="col-md-6 col-sm-6">
<div class="card-header bg-primary text-white text-center">{{ node.name }}</div>
<div class="card" style="background-color: #eee;">
<p class="font-weight-bold">Image: <img source="{{node.img.url}}"></p>
<p class="font-weight-bold">Description: <span class="font-weight-normal">{{node.description}}</span></p>
<p class="font-weight-bold">Directions: <span class="font-weight-normal">{{node.directions}}</span></p>
<p class="font-weight-bold">Elevation: <span class="font-weight-normal">{{node.elevation}}</span></p>
<p class="font-weight-bold">Latitude: <span class="font-weight-normal">{{node.latitude}}</span></p>
<p class="font-weight-bold">Longitude: <span class="font-weight-normal">{{node.longitude}}</span></p>
<p class="font-weight-bold">Added By: <span class="font-weight-normal">{{node.author}}</span></p>
<p class="font-weight-bold">Date Added: <span class="font-weight-normal">{{node.date}}</span></p>
<a class="btn btn-primary float-center" type="button" href="/EditLocation/{{node.id}}/">Edit Location</a>
</div>
</div>
{% endrecursetree %}
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'Choss_App/media')
urls.py
from django.conf.urls import url
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('Choss_App.urls')),
]
# if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
It is src=…, not source=…:
<img src="{{ node.img.url }}" …>

Django can't display the image saved in the database

I wrote two templates in Django "index.html" and "detail.html". In both templates, I display png, in the template "index" the graphics are displayed correctly, and in the template "detail" has the status "src (unknown)".
detail.html (details.html should display only one graphic)
<section class="jumbotron text-center">
<div class="container">
<h1 class="jumbotron-heading">Course Detail</h1>
<p class="lead text-muted"> {{ films.summary}}.</p>
<img class = "card-img" src="{{film.image.url}}" > </img>
<p>
Back
</p>
</div>
</section>
index.html
<div class="row">
{% for film in films.all %}
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<a href="{% url 'detail' film.id %}">
<img class = "card-img" src="{{film.image.url}}" > </img>
</a>
<div class="card-body">
<p class="card-text"> {{film.summary}} </p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Films
# Create your views here.
def index(request):
films = Films.objects.all()
return render(request, 'films/index.html',{'films':films})
def detail(request, films_id):
films_detail = get_object_or_404(Films,pk=films_id)
return render(request, 'films/detail.html',{'films':films_detail})
urls.py
from django.urls import path
from .import views
urlpatterns = [
path('', views.index, name="index"),
path('<int:films_id>', views.detail, name="detail"),
]
Before going to display any image you should make your url.py inform about it, So the right way to do this is by creating following MEDIA_ROOT and MEDIA_URL in setting.py
Managing Media
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
After that import this in url.py from setting and add it to urlpatterns
Adding URL
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
After adding this Django will Definitely Recognize your URL
The real problem in your code is that you are passing films(as Dictionary) from views.py but assessing it in templates as film
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Films
def index(request):
films = Films.objects.all()
return render(request, 'films/index.html',{'films':films})
def detail(request, films_id):
films_detail = get_object_or_404(Films,pk=films_id)
return render(request, 'films/detail.html',{'films':films_detail})
index.html
` <div class="row">
{% for film in films.all %}
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<a href="{% url 'detail' films.id %}">
<img class = "card-img" src="{{films.image.url}}" > </img>
</a>
<div class="card-body">
<p class="card-text"> {{films.summary}} </p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>`
detail.html
<section class="jumbotron text-center">
<div class="container">
<h1 class="jumbotron-heading">Course Detail</h1>
<p class="lead text-muted"> {{ films.summary}}.</p>
<img class = "card-img" src="{{film.image.url}}" > </img>
<p>
Back
</p>
</div>
</section>

How to setup the url redirect correctly after user registration and login in django?

So, I have setup django-registration's simple backend where the user registers and is immediately logged in to the display to my other django app fileuploader. Here is the urls.py:
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
from registration.backends.simple.views import RegistrationView
class MyRegistrationView(RegistrationView):
def get_success_url(self, request, user):
# return "/upload/new"
return "/upload/" + user.get_absolute_url()
urlpatterns = patterns('',
url(r'^accounts/register/$', MyRegistrationView.as_view(), name='registration_register'),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^upload/', include('mysite.fileupload.urls')),
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
import os
urlpatterns += patterns('',
(r'^media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media')}),
)
So after the user registers at accounts/register he/she is taken directly to the url upload/users/username
Here is the mysite.fileuplaod.urls that contains the url patterns for upload/:
from django.conf.urls import patterns, include, url
from mysite.fileupload.views import PictureCreateView, PictureDeleteView
from mysite.registration.backends.simple.views import RegistrationView
from django.contrib.auth.models import User
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from mysite.registration import signals
from mysite.registration.views import RegistrationView as BaseRegistrationView
class MyRegistrationView(RegistrationView):
def get_success_url(self, request, user):
# return "/upload/new"
return "/upload/" + user.get_absolute_url()
urlpatterns = patterns('',
(r'$'+get_absolute_url(),PictureCreateView.as_view(), {}, 'upload-new'),
(r'^new/$', PictureCreateView.as_view(), {}, 'upload-new'),
(r'^delete/(?P<pk>\d+)$', PictureDeleteView.as_view(), {}, 'upload-delete'),
)
I want to setup the exact same view as upload/new for upload/users/username. r'$'+get_absolute_url() doesn't look like the right way to do it. I would really appreciate if someone could show me the right way to do this.
Also I would like to display the user name on the fileupload view page as something like "Welcome
{% extends "base.html" %}
{% load upload_tags %}
{% block content %}
<div class="container">
<div class="page-header">
<h1>Wordseer File Uploader</h1>
</div>
<form id="fileupload" method="post" action="." enctype="multipart/form-data">{% csrf_token %}
<div class="row fileupload-buttonbar">
<div class="span7">
<span class="btn btn-primary fileinput-button">
<i class="icon-plus icon-white"></i>
<span>Add files...</span>
<input type="file" name="file" multiple>
</span>
<button type="submit" class="btn btn-success start">
<i class="icon-upload icon-white"></i>
<span>Start upload</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="icon-ban-circle icon-white"></i>
<span>Cancel upload</span>
</button>
<button type="button" class="btn btn-danger delete">
<i class="icon-trash icon-white"></i>
<span>Delete files</span>
</button>
<input type="checkbox" class="toggle">
</div>
<div class="span5 fileupload-progress fade">
<div class="progress progress-success progres-striped active">
<div class="bar" style="width:0%"></div>
</div>
<div class="progress-extended"> </div>
</div>
</div>
<div class="fileupload-loading"></div>
<table class="table table-striped"><tbody class="files" data-toggle="modal-gallery" data-target="#modal-gallery"></tbody></table>
</form>
<div class="fileupload-content">
<table class="files"></table>
<div class="fileupload-progressbar"></div>
</div>
<div>
{% if pictures %}
<h2>Already uploaded</h2>
<table class="table table-striped">
{% for picture in pictures %}
<tr>
<td class="preview">
<img src="{{ picture.file.url }}">
</td>
<td class="name">{{ picture.slug }}</td>
<td class="delete">
<a class="btn btn-danger" href="{% url 'upload-delete' picture.id %}">
<i class="icon-trash icon-white"></i>
<span>Delete</span>
</button>
</td>
</tr>
{% endfor %}
</table>
<p>(Removing from this list is left as an exercise to the reader)</p>
{% endif %}
</div>
</div>
<!-- modal-gallery is the modal dialog used for the image gallery -->
<div id="modal-gallery" class="modal modal-gallery hide fade" data-filter=":odd">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3 class="modal-title"></h3>
</div>
<div class="modal-body"><div class="modal-image"></div></div>
<div class="modal-footer">
<a class="btn modal-download" target="_blank">
<i class="icon-download"></i>
<span>Download</span>
</a>
<a class="btn btn-success modal-play modal-slideshow" data-slideshow="5000">
<i class="icon-play icon-white"></i>
<span>Slideshow</span>
</a>
<a class="btn btn-info modal-prev">
<i class="icon-arrow-left icon-white"></i>
<span>Previous</span>
</a>
<a class="btn btn-primary modal-next">
<span>Next</span>
<i class="icon-arrow-right icon-white"></i>
</a>
</div>
</div>
{% upload_js %}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="{{ STATIC_URL }}js/jquery.ui.widget.js"></script>
<script src="{{ STATIC_URL }}js/tmpl.min.js"></script>
<script src="{{ STATIC_URL }}js/load-image.min.js"></script>
<script src="{{ STATIC_URL }}js/canvas-to-blob.min.js"></script>
<script src="{{ STATIC_URL }}js/bootstrap.min.js"></script>
<script src="{{ STATIC_URL }}js/bootstrap-image-gallery.min.js"></script>
<script src="{{ STATIC_URL }}js/jquery.iframe-transport.js"></script>
<script src="{{ STATIC_URL }}js/jquery.fileupload.js"></script>
<script src="{{ STATIC_URL }}js/jquery.fileupload-fp.js"></script>
<script src="{{ STATIC_URL }}js/jquery.fileupload-ui.js"></script>
<script src="{{ STATIC_URL }}js/locale.js"></script>
<script src="{{ STATIC_URL }}js/main.js"></script>
<script src="{{ STATIC_URL }}js/csrf.js"></script>
{% endblock %}
Thanks in advance.
To set url use something like:
url(r"^(?P<username>\w+)/$", PictureCreateView.as_view(), {}, 'upload-new')
and move it after 'new/' url.
To display user name in template use:
{{ request.user.username }} or {{ request.user.get_full_name }}