i am trying to display image from db with views and in the inspact broswer i see it find my image but still return me 404 error. my models.py:
class HomePhoto(models.Model):
title = models.CharField(max_length=100)
img = models.ImageField(upload_to='home_page_images/')
view.py:
def index(request):
data = HomePhoto.objects.all()
return render(request, 'home.html',{'data':data,})
html:
{% for d in data %}
<img src="{{d.img}}" alt="Third slide">
{% endfor %}
url.py:
urlpatterns = [
path('',views.index,name='index')
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
the html in the broswer inspact:
<img src="home_page_images/orangeshirt_1ZrO8ay.jpg" alt="Third slide"> <!--THIS IS THE RIGHT PATH AND THE RIGHT NAME OF THE IMAGE-->
You are forgetting about accessing the url member:
{% for d in data %}
<img src="{{d.img.url}}" alt="Third slide">
{% endfor %}
{% for d in data %}
<img src="{{d.img.url}}" alt="Third slide">
{% endfor %}
you need to add url: d.img.url
Try this:
{% load static %}
<img src="{% static 'my_app/example.jpg' %}" alt="My image">
Related
Basically, what happens here, the list user_data doesn't get passed to the template, I can't figure out why. Does anyone have any ideas please? When I use the search bar I just get the else condition from the template, and it never shows any variable. I also tried to create different variables to pass to the template, but none of them got passed for some reason.
This is in my views.py:
#login_required(login_url='login_user')
def profiles(request):
context = {}
if request.method == "POST":
data = request.POST.get('search_input')
if len(data) > 0:
username_result = NewUser.objects.filter(username__icontains=data).distinct()
email_result = NewUser.objects.filter(email__icontains=data).distinct()
user_data = []
for account in username_result:
user_data.append((account, False))
context['usernames'] = user_data
return render(request, "profiles/search_user.html", context)
else:
return render(request, "profiles/profiles.html")
return render(request, "profiles/profiles.html")
Then my template looks like this:
{% extends 'profiles/base.html' %}
{% block title %}One For All{% endblock %}
{% load static %}
<!-- importing css file -->
{% block style %}<link rel="stylesheet" type="text/css" href="{% static 'css/search_user.css'
%}">{% endblock %}
{% block content %}
<!-- navigation bar -->
<div class="navBar">
<!-- logo and logo spacers -->
<div class="logo_spacer"></div>
<div class="logo"></div>
<!-- Sign Up Button -->
<a class="homeBtn" href="{% url 'profiles' %}">Home</a>
{% if is_self %}
<a class="settingsBtn" href="{% url 'settings' user=user.username %}">Profile Settings</a>
{% else %}
<a class="settingsBtn" href="{% url 'user_profile' username=user.username %}">My Profile</a>
{% endif %}
<p>Top Menu</p>
</div>
<!-- main body of login page -->
<div class="main">
{% if user_data %}
<p>We find users</p>
{% for account in user_data %}
<div>
<a class="profile-link" href="{% url 'user_profile' username=user.0.username %}">
<!--<img class="img-fluid profile-image" src="{{account.0.avatar.url}}" alt="">--></a>
</div>
{% endfor %}
{% else %}
<p>This is when user_data doesn't exist or doesn't get passed to template: {{ user_data }} </p>
{{ user_data }}
{% endif %}
</div>
<div class="bottom">
<p>Bottom</p>
</div>
{% endblock %}
{% block js_block %}
{% endblock %}
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('logout/', views.logoutUser, name='logout'),
path('post/', views.post, name='post'),
path('', views.profiles, name='profiles'),
path('search_user/', views.profiles, name='profiles'),
path('UserProfile/<str:username>/', views.user_profile, name='user_profile'),
path('Settings/<str:user>/', views.settings, name='settings'),
]
In the view you set:
context['usernames'] = user_data
But in the template you reference:
{% if user_data %}
<p>We find users</p>
{% for account in user_data %}
user_data doesn't exist in the context - you need to reference usernames instead, or change the view to call it user_data
Disquaire\urls.py
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from store import views
urlpatterns = [
url(r'^$', views.index),
url(r'^store/', include('store.urls')),
url(r'^admin/', admin.site.urls),
]
store.urls.py
urlpatterns = [
url(r'^$', views.listing, name='listing'),
url(r'^(?P<album_id>[0-9]+)/$', views.details, name="details"),
url(r'^search/$',views.search,name='search'),
]
list.html
{% for album in albums %}
<div class="col-sm-4 text-center">
<a href="/store/ {% url 'details' album_id=album.id %}">
<img class="img-responsive" src="{{ album.picture }}" alt="{{ album.title }}">
</a>
<h3>{{ album.title }}</h3>
{% for artist in album.artists.all %}
<p>{{ artist.name }}</p>
{% endfor %}
</div>
{% if forloop.counter|divisibleby:3 %}<div class="clearfix"></div>{% endif %}
{% endfor %}
views.py
def details(request, album_id):
album = Albums.objects.get(pk=album_id)
artists = " ".join([artist.name for artist in album.artists.all()])
message = "Le nom de l'album est {}. Il a été écrit par {}".format(album.title, artists)
return HttpResponse(message)
index.html
{% extends 'store\base.html' %}
{% block content %}
{% include 'store\list.html' %}
{% endblock %}
This is the error I get
Page not found
I have already tried many proposals from the site but nothing work, or maybe I didn't applied them well.I am new to Python and Django so I would appreciate all help.
You have written your urls in the manner /store/ {% url 'details' album_id=album.id %} for some reason. The url template tag will give you a relative url from the domain of your site, hence you don't have to prefix your url. Also you write src="{{ album.picture }}" here I assume picture is an image field? If so you should be writing src="{{ album.picture.url }}" instead. Hence change your template to:
{% for album in albums %}
<div class="col-sm-4 text-center">
<a href="{% url 'details' album_id=album.id %}">
<img class="img-responsive" src="{{ album.picture.url }}" alt="{{ album.title }}">
</a>
<h3>{{ album.title }}</h3>
{% for artist in album.artists.all %}
<p>{{ artist.name }}</p>
{% endfor %}
</div>
{% if forloop.counter|divisibleby:3 %}<div class="clearfix"></div>{% endif %}
{% endfor %}
I am relatively new to Django and started to create my first To-Do-List.
However I get an error whenever I try to create an href that says: NoReverseMatch at /aufgabenzettel/
I have desperately tried to fix it for the last five hours and am very frustrated because the error just seems to be caused by a single line of code... Please help! It would be awesome and I really appreciate every hint!
Here's the code:
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("<int:aufgabenzettel_id>", views.details, name="details")
]
views.py
from django.shortcuts import render
from .models import Aufgabenzettel
# Create your views here.
def index(request):
return render(request, "aufgabenzettel/index.html", {
"Aufgabenliste":Aufgabenzettel.objects.all()
})
def details(request, aufgabenzettel_id):
aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id)
return render(request, "aufgabenzettel/details.html", {
"details":aufgabenzettel
})
models.py
from django.db import models
# Create your models here.
class Aufgabenzettel(models.Model):
Aufgabeselbst = models.CharField(max_length=64)
def __str__(self):
return f"{self.Aufgabeselbst}"
layout.html
<!DOCTYPE html>
<html lang="de">
<head>
<title>Aufgabenzettel</title>
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
index.html
{% extends "aufgabenzettel/layout.html" %}
{% block body %}
<h1>Meine Aufgaben</h1>
<ul>
{% for Aufgabeselbst in Aufgabenliste %}
<li>
<a href="{% url 'details' aufgabenzettel.id %}">
Aufgabe {{ Aufgabeselbst }}
</a>
</li>
{% endfor %}
</ul>
{% endblock %}
details.html
{% extends "aufgabenzettel/layout.html" %}
{% block body %}
<h1> Aufgabe {{ details }}</h1>
Zurück zu Aufgabe
{% endblock %}
The exact error:
Reverse for 'details' with arguments '('',)' not found. 1 pattern(s) tried: ['aufgabenzettel/(?P<aufgabenzettel_id>[0-9]+)$']
Whenever I delete the line <a href="{% url 'details' aufgabenzettel.id %}"> in index.html the programme works perfectly fine...
Let me know if you need some more information!!
I really appreciate your help!
I'm new to Django. In my app, I'm working on an image uploading and displaying function. I have tried setting up the MEDIA_URL and Media_ROOT. I also add the static path to the urls.py file and make sure that in HTML template object.image.url is used. However, the image is not displayed. Any help is greatly appreciated!
Edit 1 (Add project structure):
This is a screenshot of my project structure:
link to my project structure screenshot
Edit 2 (Add screenshots of browser):
link to browser screenshot
django admin page
the image in browser
Edit 3 (Add screenshot of browser inspect window)
image of browser inspect window
My code is as followed:
urls.py
from django.contrib import admin
from django.urls import include, path
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("auctions.urls"))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
class ListingForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ListingForm, self).__init__(*args, **kwargs)
for field in iter(self.fields):
self.fields[field].widget.attrs.update({
'class': 'form-control'
})
class Meta:
model = Listing
fields = ['title', 'description', 'current_price', 'image', 'category']
def index(request):
return render(request, "auctions/index.html", {
"active_listings" : Listing.objects.all()
})
def createListing(request):
if request.method == "POST":
listing_data = ListingForm(request.POST, request.FILES)
if listing_data.is_valid():
title = listing_data['title']
description = listing_data.cleaned_data['description']
current_price = listing_data.cleaned_data['current_price']
if listing_data.cleaned_data['image']:
image = listing_data.cleaned_data['image']
else:
image = None
category = listing_data.cleaned_data['category']
listing = Listing(title=title, description=description, current_price=current_price, image=image, category=category)
listing.save()
return HttpResponseRedirect(reverse("index"))
return render(request, "auctions/createListing.html", {
"listingForm" : ListingForm()
})
models.py
class Listing(models.Model):
class Category(models.TextChoices):
FASHION = 'FA', _('Fashion')
TOYS = 'TO', _('Toys')
ELECTRONICS = 'EL', _('Electronics')
HOME = 'HO', _('Home')
OTHERS = 'OT', _('Others')
title = models.CharField(max_length=64)
description = models.TextField()
current_price = models.IntegerField()
image = models.ImageField(upload_to='listingImages', blank=True)
category = models.CharField(max_length=64, blank=True, choices=Category.choices)
settings.py
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
index.html
{% extends "auctions/layout.html" %}
{% block body %}
<h2>Active Listings</h2>
<ul>
{% for listing in active_listings %}
<li>Title: {{ listing.title }}</li>
<li>Description: {{ listing.description }}</li>
<li>Current Price: {{ listing.current_price }}</li>
{% if listing.image %}
<li>
<img scr="{{ MEDIA_URL }}{{ listing.image.url }}" alt="{{ listing.image.url }}">
</li>
{% endif %}
{% endfor %}
</ul>
{% endblock %}
createListing.html
{% extends "auctions/layout.html" %}
{% block body %}
<h1>Create A New Listing</h1>
<form action="{% url 'createListing' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% for field in listingForm %}
<div class="form-group">
{{ field.label }} {{ field }}
</div>
{% endfor %}
<input type="submit" value="Done">
</form>
{% endblock %}
Replace src attribute in your img tag from this:
scr="{{ MEDIA_URL }}{{ listing.image.url }}"
to this:
scr="{{ listing.image.url }}"
Also you can try to add a line like this to check if image exists at all:
{% if listing.image %}
<li>
<img scr="{{ MEDIA_URL }}{{ listing.image.url }}" alt="{{ listing.image.url }}">
</li>
{% else %}
<p> Image doesnt exist. </p>
{% endif %}
UPDATE
Try making your main urls.py like this:
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("auctions.urls"))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Instead of what you have right now.
I have a model with a ImageField and created an simple Upload Form via CreateForm. I have a simple ListView to show the images (logos).
Upload works fine, Iterating the logos works. Property logo.url is missing but instead it is logo.media. Unfortunately media does not contain the whole path, MEDIA_ROOT is missing. What am I doing wrong here?
models.py:
class Logo(models.Model):
media = models.ImageField(upload_to='uploads')
views.py:
class LogoManager(CreateView):
model = Logo
template_name = 'polls/upload.html'
success_url = '/logos/'
class LogoIndex(ListView):
model = Logo
template_name = 'polls/logos.html'
upload.html:
{% block title %} Upload Form {% endblock %}
{% block content %}
<form id="my_form" action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save Changes" />
</form>
<br />
Back
{% endblock %}
logos.html:
{% block content %}
{% if object_list %}
<ul>
{% for image in object_list %}
<li><img src="{{ image.media }}" width="320" height="200"/></li>
{% endfor %}
</ul>
{% else %}
<p>No Logos are available.</p>
{% endif %}
<br />
{% endblock %}
Output is:
<li><img src="uploads/IMG_5106.JPG" width="320" height="200"/></li>
You'll want to use {{ image.media.url }}, I think.
OK, it was my wrong. I was editing the url in the apps url file. When adding this stanza in root urls.py it works fine:
if settings.DEBUG:
urlpatterns += patterns('django.views.static',
(r'%s(?P<path>.*)' % settings.MEDIA_URL, 'serve', {'document_root': settings.MEDIA_ROOT}),
)
using settings.py:
MEDIA_URL = '/media/'