Django can't display the image saved in the database - django

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>

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

NoReverseMatch: Reverse for 'about' not found. 'about' is not a valid view function or pattern name

I am building blog in django and stuck because of this error.
When I click on Readmore button to load full blog post. this error appears.
it should load the page which diplay blog post with detail it showed this error to me.
i tried different solutions which are available on internet but didn't get rid of this error.
Here is my code!
project url.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('Blog_App.urls')),
]
app urls
from django.urls import path
from . import views
urlpatterns = [
path('', views.PostList.as_view(), name= 'home'),
path('user/<str:username>/', views.UserPostList.as_view(), name= 'user-posts'),
path('<slug:slug>', views.PostDetail.as_view(), name= 'post_detail'),
path('register/', views.Register, name= 'Registration'),
path('login/', views.Login, name= 'Login'),
path('logout/', views.logout_view, name= 'Logout'),
]
views.py
from django.db import models
from .forms import NewUserForm
from django.shortcuts import get_object_or_404, redirect, render
from django.http import HttpResponse
from django.contrib.auth import login,logout, authenticate
from django.contrib import messages
from django.contrib.auth.forms import AuthenticationForm
from django.views import generic
from .models import STATUS, Post
from django.contrib.auth.models import User
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'Blog_App/index.html'
class UserPostList(generic.ListView):
model = Post
template_name = 'Blog_App/user_posts.html'
context_object_name = 'posts'
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return Post.objects.filter(author=user).order_by('-created_on')
class PostDetail(generic.DetailView):
model = Post
template_name = 'Blog_App/post_detail.html'
def Register(request):
if request.method == 'POST':
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
messages.success(request, 'Registration succesfull')
return redirect('home')
messages.error(request, 'Invalid Information')
form = NewUserForm()
context = {'register_form': form}
return render(request, 'Blog_App/register.html', context )
def Login(request):
if request.method == 'POST':
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
messages.info(request, 'Congrats. You logged In! ')
return redirect('home')
else:
messages.error(request, 'Incorrect Credentials!')
else:
messages.error(request, 'Invalid Information')
form = AuthenticationForm()
return render(request, 'Blog_App/login.html', context={'login_form': form})
def logout_view(request):
logout(request)
messages.info(request, 'You are succesfully Logged out')
return redirect('home')
Base.html
<!DOCTYPE html>
<html lang="en">
{% load static %}
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blog-App</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
</head>
<body>
<div class="nav-container">
<nav class="test">
<div class="nav-wrapper">
<a href="#" data-target="mobile-demo" class="sidenav-trigger"><i class="material-
icons">menu</i></a>
<ul id="nav-mobile" class="hide-on-med-and-down">
<li>Home</li>
<li>About </li>
<li>Contact Us</li>
<ul id="nav-mobile" class="right hide-on-med-and-down">
{% if user.is_authenticated %}
<li>Logout</li>
<li>{{user.username}}</li>
{% else %}
<li>Login</li>
<li>Register</li>
{% endif %}
</ul>
<div>
</nav>
</div>
{% block content %}
{% endblock content %}
<footer class="page-footer" >
<div class="container">
<div class="row">
<div class="col l6 s12">
<h5 class="white-text">Footer Content</h5>
<p class="grey-text text-lighten-4">You can use rows and columns here to organize your
footer content.</p>
</div>
<div class="col l4 offset-l2 s12">
<h5 class="white-text">Links</h5>
<ul>
<li><a class="grey-text text-lighten-3" href="#!">Link 1</a></li>
<li><a class="grey-text text-lighten-3" href="#!">Link 2</a></li>
<li><a class="grey-text text-lighten-3" href="#!">Link 3</a></li>
<li><a class="grey-text text-lighten-3" href="#!">Link 4</a></li>
</ul>
</div>
</div>
</div>
<div class="footer-copyright">
<div class="container">
© 2014 Copyright Text
<a class="grey-text text-lighten-4 right" href="#!">More Links</a>
</div>
</div>
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js">
</script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
{% if messages %}
{% for msg in messages %}
<script>
swal({
"text": "{{msg}}",
});
</script>
{% endfor %}
{% endif %}
</body>
</html>
index.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="Blog-posts">
<div class="row">
<div class="div-1">
<div class="col s12 m6 ">
{% for post in post_list %}
<div class="card card-list blue-grey darken-1">
<div class="card-content white-text">
<div class="author">
<a href="{% url 'user-posts' post.author.username %}">
<h5 class="author-name"><img class="author-img" src="{% static
'images/profile.jpg' %}" alt="" height="40px" width="40px">
{{post.author}}</h5>
</a>
<small class="post-created_on">{{post.created_on}}</small>
</div>
<span class="card-title">{{post.title}}</span>
<p>{{post.content|slice:"200"}}</p>
</div>
<div class="Readmore-btn">
<a href="{% url 'post_detail' post.slug %}" class="waves-effect waves-
light btn-small">Read More</a></div>
</div>
{% endfor %}
</div>
</div>
<div class="div-2">
<div class="col m5">
<div class="card card-sidebar">
<div class="card-content black-text">
<span class="card-title">About Us</span>
<p>I am a very simple card. I am good at containing small bits of
information.
I am convenient because I require little markup to use effectively.</p>
</div>
<div class="card-action">
<div class="Readmore-btn_about"><a href="#" class="waves-effect waves-
light btn-small">Read More</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock content %}
If you are facing same kind of issue. so here how i get rid of this.
Django giving me error of some kind of {% url 'about' %} pattern in base.html.
But it actually exist in another html file which called as post_detail.html.
So if you are facing same kind of error check for other files as well you will find an error in other html file.
Thanks

My view isn't rendering any result in the template - 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()))

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 create form with materialize modal

As far as I tried, I cannot get the form data or send it to the django view function through the materialize css modal. I'm just a novice in js, ajax and related.
The "CreateView" action for my form is running outside, but it is required to be inside a modal and still get the benefits of using django form validation, security, and so on. I'm using Django version 1.11.
The project has two applications: main that loads the main page, and library that performs actions on book objects. A book has only a title, and so there's a form defined like:
library/forms.py:
from django import forms
from .models import Book
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = [
'title',
]
the project urls definition, mysite/urls.py :
from django.conf.urls import url, include
from django.contrib import admin
from main import views as main_views
urlpatterns = [
url(r'^$', main_views.home, name='home'),
url(r'^books/', include('library.urls')),
url(r'^admin/', admin.site.urls),
]
Home view, main/views.py:
from django.shortcuts import render
def home(request):
return render(request, 'main/home.html')
main/templates/main/home.html:
<html>
<head>
<title>A library</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
{% block body %}
<div class="container">
<!--a class="waves-effect waves-light btn modal-trigger" href="#modal1">Create Book</a-->
<a class="waves-effect waves-light btn modal-trigger" data-target="add_book_modal" href="{% url 'books:create' %}">
Create Book
</a>
<div class="divider"></div>
<div class="section">
<h5>Section 1</h5>
<p>Stuff</p>
</div>
</div>
{% endblock %}
{% include 'library/book_form.html' %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<script>
$( document ).ready(function() {
$('.modal').modal();
});
</script>
</body>
</html>
The library's urls, library/urls.py:
from django.conf.urls import url
from .views import BookCreateView
app_name='books'
urlpatterns = [
url(r'^create/$', BookCreateView.as_view(), name='create'),
]
library/views.py:
from django.shortcuts import render
from django.views.generic import CreateView
from django.urls import reverse_lazy
from .models import Book
from .forms import BookForm
class BookCreateView(CreateView):
form_class = BookForm
template_name = 'library/book_form.html'
success_url = reverse_lazy('home')
library/templates/library/book_form.html:
<div id="add_book_modal" class="modal">
<div class="modal-content">
{% block body %}
<main>
<h5>Add book information</h5>
{% if form.errors.non_field_errors %}
{{ form.errors.non_field_errors }}
{% endif %}
<form method="POST">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.source.errors }}
{{ form.source }}
<!--Form content-->
{{form.as_p}}
<!--Form button-->
<button class="btn waves-effect waves-light" type="submit" name="action">Submit
</button>
</form>
</main>
{% endblock %}
</div>
</div>
Any help will be appreciated.
Changing a href link and setting the place of html code where the content will be rendered
main/templates/main/home.html:
...
<a class="waves-effect waves-light btn modal-trigger" href="#modal1">Create Book</a>
...
<!-- Modal Structure -->
<div id="modal1" class="modal">
<div class="modal-content">
<!--Form content goes in here.-->
</div>
</div>
{% endblock %}
<!-- django include tag removed -->
Jquery to render the form in the modal through django's routes
main/templates/main/home.html:
<script>
$( document ).ready(function() {
$('.modal').modal();
$('.modal-content').load("{% url 'books:create' %}");
});
</script>
Finally, book form specifying the way back.
_library/templates/library/book_form.html_:
<h5>Add book information</h5>
{% if form.errors.non_field_errors %}
{{ form.errors.non_field_errors }}
{% endif %}
<form method="POST" action="{% url 'books:create' %}">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.source.errors }}
{{ form.source }}
<!--Form content-->
{{form.as_p}}
<!--Form button-->
<button class="btn waves-effect waves-light" type="submit" name="action">Submit form
</button>
</form>