i can't load a img from my instance image - django

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)

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 images not showing up

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')

Django form not visible after redirect

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'),
]

How to fix "Not Found" problem for displaying images?

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.

Reverse for 'register' not found. 'register' is not a valid view function or pattern name

I'm trying to make a simple app that uses the django built-in User model. I have created a registration page, but when I run the server, I get this error at the index page. Here's the code I'm using:
Registration.html
<!DOCTYPE html>
{% extends "basic/base.html" %}
{% block title_block %}
<title>Registration</title>
{% endblock title_block %}
{% block body_block %}
<div class="jumbotron">
{% if registered %}
<h1>Thank you for registering</h1>
{% else %}
<h1>Register here!</h1>
<h3>Fill out the form: </h3>
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
{{userForm.as_p}}
{{profileForm.as_p}}
<input type="submit" value="Register" name="">
</form>
{% endif %}
</div>
{% endblock body_block %}
Views.py for the 'register' method
def register(request):
registered = False
if(request.method == 'POST'):
userForm = forms.UserForm(data=request.POST)
profileForm = forms.UserProfileInfoForm(data=request.POST)
if((userForm.is_valid()) and (profileForm.id_valid())):
user = userForm.save()
user.set_password(user.password)
user.save()
profile = profileForm.save(commit=False)
profile.user = user
if('profileImage' in request.FILES):
profile.profileImage = request.FILES['profileImage']
profile.save()
registered = True
else:
print(userForm.errors, profileForm.errors)
else:
userForm = forms.UserForm()
profileForm = forms.UserProfileInfoForm()
return render(request, 'basic/registration.html', {'userForm':userForm, 'profileForm':profileForm, 'registered':registered})
This is the urls.py for the project
from django.contrib import admin
from django.urls import path, include
from basic import views
urlpatterns = [
path('', views.index, name='index'),
path('admin/', admin.site.urls),
path('basic/', include('basic.urls', namespace='basic'))
]
This is the urls.py for the basic app
from django.urls import path
from . import views
app_name = 'basic'
urlpatterns = [
path('register/', views.register)
]
And the link to the page in base.html
<a class="nav-link" href="{% url 'basic:register' %}">Register</a>
What can cause the error here?
You must include a name argument to the register route.
path('register/', views.register, name='register')
https://docs.djangoproject.com/en/2.1/topics/http/urls/#reverse-resolution-of-urls
try this (inside your html file)
<a class="nav-link" href={% url 'basic:register' %}>Register</a>
and your urls.py (inside your app) as this:
urlpatterns = [
path('register/', views.register,name='register'),
]
this method worked for me I was fasing the same issue.