Django images not showing up - django

I've spent hours looking for a solution, figured I would post for myself. Django images won't show.
models.py:
class Item(models.Model):
...
image = models.ImageField(default='default.jpg', upload_to='item_pics')
urls.py
from django.urls import path
from . import views
from .views import ItemListView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', ItemListView.as_view(), name="site-home"),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
html-file
{% extends "ui/base.html" %}
{% load static %}
{% block content %}
<ul>
{% for item in items %}
<li>
<p><img src="{{ item.image.url }}"></p>
<br>
</li>
{% endfor %}
</ul>
{% endblock content %}
It shows up like this:
When I copy image address, I get http://localhost:8000/media/default.jpg

There is no image at http://localhost:8000/media/default.jpg. Are you sure the path is correct? You uploaded way too little code. It seems like it should be http://localhost:8000/item_pics/default.jpg? Does that link work?
If I'm right, try this in models.py:
image = models.ImageField(default='default.jpg', upload_to='media')

Related

Django: custom button in admin change form return bad url for custom view function

I have problems to link my custom button from change_form.html to my view function.
pic : admin change form custom button
change_form.html
{% extends "admin/change_form.html" %}
{% load i18n %}
{% block title %} Send Email {% endblock %}
{% block content %}
{% if request.resolver_match.url_name == 'requests_requests_change' %}
<div class="submit-row">
{% csrf_token %}
<a href="{% url 'requests:send-email' original.pk %}"
class="button" style="background-color: #F08000;float: left">Request Subscription
</a>
</div>
{% endif %}
{{ block.super }}
{% endblock %}
views.py
from django.shortcuts import render, redirect
def send_email(request, requests_id):
return redirect('') # or whatever to test the url
urls.py
from django.urls import path
from . import views
app_name = 'requests'
urlpatterns = [
path('<int:pk>/send-email/', views.send_email, name='send-email'),
]
main project 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.site.urls), # admin site administration
path('requests/', include('requests.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
pic: error message
Any help would be great! Thanks!
I have found the solution on my own.
The issue was the url inside the template.
Worked with this one:
Template :
<a href="{% url 'admin:requests_requests_change' original.pk %}send-email/"
And the URL path:
path('<int:pk>/change/send-email/', views.send_email, name='send-email')

django template internal url concatenation

In my django project, I have URL patterns like below.
urls.py in project root:
urlpatterns = [
path('', include('blog.urls')),
]
urls.py in app(blog) root:
urlpatterns = [
path('', views.index, name='index'),
path(
'category/<str:category_id>',
views.category_view,
name='category_view',
),
]
What I want to do is making hyperlink for each category with django template. Something like below.
{% for category in categories %} .
<a href="{{ {% url 'index' %}|add: {% url 'category_view' category %} }} " class="nav">
{{category}}
</a>
{% endfor %}
However, it doesn't work. There are too many categories that I can't hard code any of them, but have to make url "(domain root)/category/(category name)" with django template. How can I concatinate two url in a template (as django does with
path(A, include(B))
)
You can define a get_absolute_url method in your Category model, it is a much cleaner solution: https://docs.djangoproject.com/en/2.1/ref/models/instances/#get-absolute-url
Implementation example:
from django.urls import reverse_lazy
# for django < 1.10 from django.core.urlresolvers import reverse_lazy
class Category(models.Model):
...
def get_absolute_url(self):
return reverse_lazy('category_view', category_id=self.id)
and in your template:
{% for category in categories %} .
<a href="{{ category.get_absolute_url }}" class="nav">
{{category}}
</a>
{% endfor %}

why i am not able to view with classbased (list view )but for function based view it is working fine?

My question: why i am not able to view search only ayan rand's book with classbased list view?
this is my function based view for store list, and i am retrieving all my book objects and rendering in HTML and it is working fine.
But using classbasedview "SearchBookDetail" i am not able to get the specified book details as denoted .
Views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect
from django.views.generic import TemplateView,ListView,DetailView
def store_listView(request,):
queryset=Book.objects.all()
context={
"objects_list":queryset
}
return render(request,'bookstores/store.html',context)
class SearchBookDetail(ListView):
template_name = "bookstores/store.html"
queryset = Book.objects.filter(author__icontains='Ayan Rand')
print("Ayan Rand query set", queryset)
Urls.py:
from django.conf.urls import url
from django.contrib import admin
from django.views.generic import TemplateView
from store.views import (Home,ContactView,LoginView,
store_listView,
SearchBookDetail,
book_createview,
QuoteslistView,
AyanRandBookDetail,
quotesFunctionView)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',Home.as_view()),
url(r'^contact/$',ContactView.as_view()),
url(r'^login/$',LoginView.as_view()),
url(r'^store/$',store_listView),
url(r'^store/AyanRandBookDetail/$',AyanRandBookDetail.as_view()),
url(r'^store/SearchBookDetail/$',SearchBookDetail.as_view()),
url(r'^quotes/$',quotesFunctionView)]
store.html:
{% extends "home.html" %}
{% block head_title %}Store || {{ block.super }} {% endblock head_title %}
{% block content %}
<head>
<meta charset="UTF-8">
<title>Store</title>
</head>
<h6>Books available</h6>
<ul>
{% for obj in objects_list %}
<li>{{obj}}<br>
{{obj.book_image}} <br>
{{obj.description}} <br>
{{obj.author}}<br>
{{obj.genre}}<br>
{{obj.price}}<br>
</li>
{% endfor %}
</ul>
{% endblock content %}
ListView sends its data to the template as object_list, not objects_list.

i can't load a img from my instance image

hi im trying load a image from my media folder and is not working, i have as output that my {{ image.image.url }} display /media/products/yo.jpg here is my structure
this is my block where i want to load the images that are in the instance of images.
also i think my code is not good maybe you can give some advice.
{% block content %}
<!-- all products-->
<section >
{% for product in products %}
{% for image in images %}
<div class="product">
<img src="{% static 'img/vaca.jpg' %}" class="imgpro">
<div class="info">
<p>
<h3> Product: </h3> {% if image.product.pk == product.pk %} <img src='{{ image.image.url }}' class="imgpro"> {% endif %}
<h3> Offer: </h3> {{ product.product }}
<h3> Description: </h3> {{ product.description }}
</p>
</div>
</div>
{% endfor %}
{% endfor %}
</section>
{% endblock content %}
this is my urls:
from django.conf.urls import include, url
from . import views
from django.contrib.auth.views import login
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.views import logout
app_name = 'ganagroapp'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^product/(?P<pk>[0-9]+)/$', views.product_detail, name='product_detail'),
url(r'^category/(?P<pk>[0-9]+)/$', views.product_category, name='product_category'),
url(r'^product/new/$', views.new_product, name='new_product'),
url(r'^login/$',login,{'template_name':'login.html'}, name='login'),
url(r'^logout/$',logout,{'template_name':'index.html'},name='logout'),
]
this is my view
def index(request):
images = Image.objects.select_related()
category = Category.objects.select_related()
products = Product.objects.select_related()
return render(request,'ganagroapp/index.html', {'category' : category, 'products' : products, 'images': images} )
this is the settings file
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
MEDIA_ROOT = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'ganagroapp', 'media')
LOGIN_REDIRECT_URL = reverse_lazy('ganagroapp:index')
I think the problem is occured because you did not add the last line in your urls.py:
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
]
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

Django NoReverseMatch at /pet/

I'm working on simple a pet store app
I encountered this error a couple of times and I managed to understand it and fix it but in this situation . I don't know what went wrong . Everything seem clear to me .
It says I have an error in my store.html at the location of the {% url world:brazil animal.id %} but I have define the namespace already.
Reverse for 'brazil' with arguments '('',)' and keyword arguments '{}' not found.
Error during template rendering
In template C:\djcode\mysite\pet\templates\store.html, error at line 5
Reverse for 'brazil' with arguments '('',)' and keyword arguments '{}' not found.
1 Sydney's Pet Store
2 {% if store %}
3 <ul>
4 {% for a in store %}
5 <li><a href ="{% url world:brazil animal.id %}">{{ a.name }}</li>
6 {% endfor %}
7
8 </ul>
9 {% endif %}
My store.html
Sydney's Pet Store
{% if store %}
<ul>
{% for a in store %}
<li><a href ="{% url world:brazil animal.id %}">{{ a.name }}</li>
{% endfor %}
</ul>
{% endif %}
My views.py
from pet.models import Store , Pet
from django.shortcuts import render_to_response ,get_object_or_404
def index(request):
store = Store.objects.all()
return render_to_response ('store.html',{'store':store})
def brazil(request , animal_id):
store = get_object_or_404(Store , Pet, pk=animal_id)
return render_to_response ('animal.html',{'store':store})
My pet app URLCONF:
from django.conf.urls import patterns,include , url
urlpatterns = patterns ('pet.views',
url(r'^$','index',name = 'index'),
url(r'^(?P<poll_id>\d+)/$','brazil',name ='brazil'),
)
my main URCONF:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = patterns('',
url(r'^pet/',include('pet.urls' , namespace='world' )),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
Because you didn't define animal.id. What you have render in your view is only store variable.
Sydney's Pet Store
{% if store %}
<ul>
{% for a in store %}
<li><a href ="{% url world:brazil a.id %}">{{ a.name }}</li>
{% endfor %}
</ul>
{% endif %}