I'm preparing a blog component of a site, it is created inside an app of a project. It seems that there is no problem except the images are not displayed.
while running, all things are OK, but just the image "alt" is displayed instead of the image. I have images without problem in other pages of this project.
There is a report on Terminal:
"Not Found: /article/static/images/growth_EWAl68g.png
[14/Apr/2019 17:44:38] "GET /article/static/images/growth_EWAl68g.png HTTP/1.1" 404 6164"
As you can see, Django uses a false address (static folder is located in root of projects) to access the images.
class BlogArticle(models.Model):
title = models.CharField(max_length=150)
headline = models.CharField(max_length=300)
body = models.TextField()
post_image = models.ImageField(upload_to ="static/images")
date = models.DateTimeField(auto_now_add=True)
author = models.CharField(max_length=100)
def __str__(self):
return self.title
class ArticleListView(ListView):
model = BlogArticle
template_name = 'article_list.html'
urlpatterns = [
path('', views.HomeView, name= 'home'),
path('article/', views.ArticleListView.as_view(), name='article_list'),
path('article/<int:pk>/', views.ArticleDetailView.as_view(), name='article_detail'),
.
.
.]
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('accounts/', include('allauth.urls')),
path('contactus', include('sendemail.urls')),
path('', include('myapp.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
{% block content %}
<div <div class="container mt-5 bg-light">
{% for article in object_list %}
<div class="form-row">
<div class="form-group col-sm-9 ">
<div class="post-entry">
<h5 > <a href = "{% url 'article_detail' article.pk %}" > {{ article.title }}</a></h5>
<div>
<p class="font-weight-bold"> {{article.headline }} </p>
</div>
<div>
<span class="text-muted">by {{article.author }} | {{ article.date|date:"M d, Y"}}</span>
</div>
</div>
</div>
<div class="form-group col-sm-3 ">
<div class="thumbnail">
<img src="{{article.post_image}}" width=100 height=100 class="rounded" alt="{{article.title}}">
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
.
DEBUG = True
ALLOWED_HOSTS = []
.
.
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]
.
.
I can't understand this condition, It seems that Django should go to static/images/ but it has an extra word (article) at the beginning of the address.
This problem was simply solved by adding
urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
to project's urls.py and
MEDIA_URL = '/media/'
in settings.py.
Related
My project is to build a supermarket website.customers can input the quantity of the products so that I can calculate price.I use the first product 'apple' to test for whether I can get the typing integer by the customers and show on the price.html.
My expected result is '1'I have tried many times but
it still show none.Can anyone help me?
my views code is like this:
def price(request):
a = request.GET.get('apple')
return render(request, 'price.html', {'a': a})
meat-series html file is like:
{% block content %}
<body>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
{% for ser in meat_ser %}
<div style="position:sticky ;" class= "row" >
<div class="col-sm-6">
<div class="card mb-3 " style="width: 18rem;">
<img style="height: 250px;margin: 0%;" id='photo'src="{{ser.photo}}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{ser.Name}}</h5>
<p class="card-text"></p>
<form action="price/" >
<label form='price/'>Qualitiy:</label>
<input type="number" name={{ser.Name}}>
<input type="submit" value="Buy">
</form>
The urls file is like this:
from django.urls import path, re_path
from . import views
app_name = 'web'
urlpatterns = [
path('', views.index, name='index'),
re_path(r'^login/', views.login_request, name='login'),
re_path(r'^register/', views.register_request, name='register'),
re_path(r'^meat_series/', views.meat_series, name='meat_series'),
path('logout/', views.logout_request, name='logout'),
path('price/', views.price, name='price')
]
The url showed when submitted is: http://127.0.0.1:8000/web/meat_series/price/?apple=1
I'm trying to make django form to appear after user is logged in and authenticated but the form just does not appear on the page here is my code. I'm stuck on this for few days now and any help would be huge help
Views.py form code
def prasymas(request):
context = initialize_context(request)
user = context['user']
form = Prasymas(request.POST or None)
if form.is_valid():
form.save()
context ={
'form':form
}
return HttpResponseRedirect(reverse('home'))
urls.py code
from django.urls import path
from . import views
urlpatterns = [
# /
path('', views.home, name='home'),
# TEMPORARY
path('signin', views.sign_in, name='signin'),
path('signout', views.sign_out, name='signout'),
path('callback', views.callback, name='callback'),
path('prasymas', views.home, name='prasymas'),
]
template.py code
{% extends "loginas/layout.html" %}
{% block content %}
<div class="container">
<h1 class="d-flex justify-content-center"></h1>
<p class="d-flex justify-content-center"></p>
{% if user.is_authenticated %}
<h4>Sveiki {{ user.firstname }} {{user.surname}}
</h4>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-secondary">POST</button>
</form>
{% else %}<div class="d-flex justify-content-center">
Prisijungti
</div>
{% endif %}
</div>
{% endblock %}
From your urls.py it looks like the prasymas function in views.py is not being called.
Try making the following change to your urls.py file to include a call to the prasymas function.
Note: the line path('prasymas', views.prasymas, name='prasymas'), now points to views.prasymas not home. This means the path /prasymas will now render your form.
from django.urls import path
from . import views
urlpatterns = [
# /
path('', views.home, name='home'),
# TEMPORARY
path('signin', views.sign_in, name='signin'),
path('signout', views.sign_out, name='signout'),
path('callback', views.callback, name='callback'),
path('prasymas', views.prasymas, name='prasymas'),
]
files of whole project
I have correctly setup path for media url and still not able to find images in allproducts.html where as in categories.html it is able to find images from media directory. I am not able understand the cause of this bug.
allproducts.html
{% for sub in subcategory %}
{% for p in sub.product_set.all %}
<div class="product">
<div><h3 class="logo header_content d-flex flex-row align-items-center justify-content-start">{{sub.name}}</h3></div>
<div class="product_image"><img src="media/{{p.image}}" alt=""></div>
<div class="product_content">
<div class="product_title">{{p.name}}</div>
<div class="product_price">{{p.price}}</div>
</div>
</div>
{% endfor %}
<div></div>
{% endfor %}
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
STATIC_DIR,
]
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
urls.py
urlpatterns = [
path('',views.index, name="index"),
path('cart',views.cart, name="cart"),
path('categories',views.categories, name="categories"),
path('checkout',views.checkout, name="checkout"),
path('contact',views.contact, name="contact"),
path('product/<int:pk>/',views.product, name="product"),
path('allproducts/<int:pk>/', views.allproducts, name="allproduct"),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
def allproducts(request, pk):
products = Product.objects.all()
category = Category.objects.get(pk=pk)
subcategory = Subcategory.objects.filter(category = category)
return render(request, 'shop/allproducts.html',
{'products':products, 'subcategory':subcategory,
'category':category})
project files
kh
kh
.idea
__init__.py
settings.py
urls.py
wsgi.py
media
shop
images
test.jpg
shop
db.sqlite3
manage.py
You will certainly need a leading slash:
<img src="/media/{{p.image}}" alt="">
But better to let the image itself output its full path:
<img src="{{p.image.url}}" alt="">
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)
I am trying to display images that have been uploaded by the user, but no matter what I try I am getting the broken link icon. I have searched and searched through the documentation, on SO and elsewhere for a couple of days now to no avail. I am new to Django and currently in development so I'm sure I've made some other rookie mistakes, but right now the only thing I care about is displaying uploaded images in templates.
Here are the relevant snippets of my code:
settings.py
MEDIA_URL = '/media/media_root/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media", "media_root")
urls.py
urlpatterns = [
url(r'^admin/?', admin.site.urls),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^about/?', profiles.views.about, name='about'),
url(r'^properties/single/?', properties.views.single, name='single_mens'),
url(r'^properties/married/?', properties.views.married, name='married'),
url(r'^properties/add/add_photos/?', properties.views.add_photos, name='add_photos'),
url(r'^properties/add/?', properties.views.add_rental, name='add_rental'),
url(r'^', profiles.views.home, name='home'),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
models.py
class RentalPicModel(models.Model):
def __unicode__(self):
return self.image.url
image = models.ImageField(upload_to="pics/originals/", null=True)
rental = models.ForeignKey(RentalModel, on_delete=models.CASCADE)
forms.py
class AddPhotosForm(forms.ModelForm):
class Meta:
model = RentalPicModel
fields = ['image', 'rental']
def clean_image(self):
return self.cleaned_data['image']
def clean_rental(self):
return self.cleaned_data['rental']
views.py
def add_photos(request):
form = AddPhotosForm
current_rental = None
current_photos = []
if request.method == "POST":
form = AddPhotosForm(request.POST, request.FILES)
if request.POST.get('another'):
if form.is_valid():
cleaned_image = form.cleaned_data['image']
cleaned_rental = form.cleaned_data['rental']
current_rental = cleaned_rental
pic = RentalPicModel(image=cleaned_image, rental=cleaned_rental)
pic.save()
current_photos = RentalPicModel.objects.filter(rental=current_rental)
current_photos = [rental.image for rental in current_photos]
for photo in current_photos:
print photo
context = {
'form' : form,
'photos' : current_photos,
}
return render(request, "add_photos.html", context)
Here the output of the print statement (after uploading one photo) is: pics/originals/DSC_1376.jpg and I can see the file is saved to that location.
add_photos.html
<div class="container">
<h1>Upload your photos here.</h1>
<br>
<div class='row'>
<form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %}
{{ form|crispy }}
<div class='col col-xs-3'></div>
<div class='col col-xs-3'>
<input class="btn btn-block btn-info" name="another" type="submit" value="Save and Add Another">
</div>
<div class='col col-xs-3'>
<input class="btn btn-block btn-primary" name="finish" type="submit" value="Save and Finish">
</div>
<div class="col col-xs-3"></div>
</form>
</div>
{% if photos|length > 0 %}
<h2>Uploaded photos:</h2>
{% for photo in photos %}
<div class='row'>
<img src="{{ photo.url }}" alt="">
</div>
{% endfor %}
{% endif %}
</div>
When I inspect the <img> element, I see src="/media/media_root/pics/originals/DSC_1376.jpg" which gives me a url of http://127.0.0.1:8000/media/media_root/pics/originals/DSC_1376.jpg. This seems to be the correct file location to me, but it is still not displaying.
Like I say, everything seems to me to be set up how it is described in the Django documentation and in every other question I've read on SO. What am I missing?
Thank you in advance.
EDIT
Do I need to modify my STATICFILES_DIRS setting at all for uploaded media? Here is what I have right now:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static_files"),
)
which is where I've put all my CSS and javascript files.
You forgot to concatenate the MEDIA_URL and the {{ photo.url }}.
Try:
<img src="{% get_media_prefix %}{{ photo.url }}" alt="">
More about {% get_media_prefix %} HERE in the docs.
My urls were the problem. When it was trying to retrieve the media files, it matched url(r'^', profiles.views.home, name='home') before it matched any of the media urls. A simple $ fixed it:
url(r'^$', profiles.views.home, name='home')