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 }}" …>
Related
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()))
I'm attempting to use an API as part of a project I'm working on and am having some difficulty currently:
API
https://developers.amadeus.com/self-service/category/air/api-doc/airport-and-city-search
API - Python SDK
https://github.com/amadeus4dev/amadeus-python
Django API Guide
https://developers.amadeus.com/blog/django-jquery-ajax-airport-search-autocomplete
I have followed the instructions from the above guide; however, I am receiving the following error when trying to render the index page which contains the code:
Reverse for 'origin_airport_search' not found. 'origin_airport_search' is not a valid view function or pattern name.
Index Template:
{% extends "flightfinder/layout.html" %}
{% block body %}
<div id="mainhomepagediv">
<div class="container-fluid px-0" id="mainhomepagediv">
<div class="row mx-0">
<div class="col-12 px-0">
<img src="https://i.ibb.co/rHYzcyc/Landscape2.jpg" class="img-fluid w-100">
</div>
</div>
</div>
<div>
<h1 id="homepageh1">Where are you flying to?</h1>
<div id="homepagebox">
<div>
<form id="homepageform" method="POST">
<div class="row">
<div class="col">
<label id="homepageformlabel">From</label>
<input type="text" class="form-control" placeholder="Origin city" id="inputOrigin">
</div>
<div class="col pb-3">
<label id="homepageformlabel">To</label>
<input type="text" class="form-control" placeholder="Destination city">
</div>
</div>
<div class="row">
<div class="col">
<label id="homepageformlabel">Depart</label>
<input type="date" class="form-control" placeholder="Origin city">
</div>
<div class="col">
<label id="homepageformlabel">Return</label>
<input type="date" class="form-control" placeholder="Destination city">
</div>
<div class="col-6">
<label id="homepageformlabel">Class</label>
<select id="inputState" class="form-control">
<option selected>Economy</option>
<option>Business</option>
<option>First</option>
</select>
</div>
</div>
<div class="row">
<div class="col">
</div>
<div class="col-3 pt-3">
<button class="btn float-right" id="homepageformbutton" type="submit">Search flights</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
// Amadeus origin airport search
$(document).ready(function () {
$("#inputOrigin").autocomplete({
source: "{% url 'origin_airport_search' %}",
minLength: 1,
delay: 200,
});
});
</script>
{% endblock %}
Layout Template:
{% load static %}
<!doctype html>
<html lang="en">
<head>
<!-- jQuery & jQuery UI -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!-- Bootstrap (includes Popper) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Main CSS-->
<link rel="stylesheet" type="text/css" href="{% static 'flightfinder/styles.css' %}">
<!-- Main JS -->
<script src="{% static 'flightfinder/main.js' %}"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<!-- Font Awesome Icons -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
<title>{% block title %}Flight Finder{% endblock %}</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light">
<a class="navbar-brand" href="{% url 'flightfinder:index' %}">
<img src="https://i.ibb.co/TRBkPBZ/Flight-Finder-removebg-preview.png" width="166" height="42" class="d-inline-block align-top" alt="">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<a class="nav-item nav-link active" href="{% url 'flightfinder:index' %}">Flights <span class="sr-only">(current)</span></a>
<a class="nav-item nav-link" href="#">Hotels</a>
<a class="nav-item nav-link" href="#">Car Hire</a>
</div>
</div>
</nav>
{% block body %}
{% endblock %}
</body>
</html>
Main - urls.py:
"""finalproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/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 include, path
urlpatterns = [
path('', include('flightfinder.urls', namespace='Flightfinder')),
path('admin/', admin.site.urls),
]
App - urls.py:
from django.urls import path
from . import views
app_name = 'flightfinder'
urlpatterns = [
path('', views.index, name='index'),
path('origin_airport_search/', views.origin_airport_search, name='origin_airport_search')
]
views.py:
import json
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib import messages
from amadeus import Client, ResponseError, Location
from .models import Airport, Flight, Passenger
amadeus = Client(client_id='removed',
client_secret='removed',
log_level='debug')
# Create your views here.
def index(request):
return render(request, 'flightfinder/index.html')
def origin_airport_search(request):
if request.is_ajax():
try:
data = amadeus.reference_data.locations.get(keyword=request.GET.get('term', None), subType=Location.ANY).data
except ResponseError as error:
messages.add_message(request, messages.ERROR, error)
return HttpResponse(get_city_airport_list(data), 'application/json')
def get_city_airport_list(data):
result = []
for i, val in enumerate(data):
result.append(data[i]['iataCode']+', '+data[i]['name'])
result = list(dict.fromkeys(result))
return json.dumps(result)
I have had a look through some similar stack queries, but none of them have helped thus far. Would be grateful if somebody had any ideas to try here?
Thank you!
You have set a namespace "Flightfinders" in your include. This means you have to use this namespace to call your URL:
source: "{% url 'Flightfinder:origin_airport_search' %}",
I need slider in my website and I have tried these things as mentioned below but I cannot get the data from the database in template. Is the process of getting data from database is wrong. How to get the data in template I am really confused how to do these things.
Model.py
class AddImage(models.Model):
name=models.CharField(max_length=100,blank=False)
image=models.ImageField(upload_to='img')
publish=models.BooleanField(default=True)
def __str__(self):
return self.name
views.py
def index(request):
slider_img=AddImage.objects.all()
context = {
'slider_img':slider_img
}
return render(request,'home.html',context)
home.html
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
{% for img in slider_img %}
{% if img.publish %}
<div class="carousel-item active">
<img class="d-block w-100" src="{{ img.image.url }" alt="First slide">
</div>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
{% endif %}
{% endfor %}
</div>
</div>
Reference : https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user-during-development
Check your settings.py, that you have defined MEDIA_ROOT and 'MEDIA_URL' (and they are correct).
And add these lines to the end of your urls.py file:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
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>
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 }}