add image to FileField in Django - python

I'm using Django building a website and I'm trying to let the user upload an image to be used, here is my files :
settings.py
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home2/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
models.py
class test1(models.Model):
dress_name = models.CharField(max_length=250, default='dress')
dress_size = models.CharField(max_length=50, default='5')
docfile = models.FileField(upload_to='documents/%Y/%m/%d',default ='upload')
views.py
def home(request):
all_dress = test1.objects.all()
context = {
'all_dress': all_dress,
}
return render(request, 'fostania/home.html', context)
and here is how I used it in my template
HTML
{% for item in all_dress %}
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="{{ item.docfile.url }}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{ item.dress_name }}</h5>
<p class="card-text">{{ item.dress_size }}</p>
Go somewhere
</div>
</div>
{% endfor %}
URLS.py
from django.contrib import admin
from django.template.context_processors import static
from django.urls import path
from django.contrib.auth import views as auth_views
from dress import settings
from fostania import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', auth_views.login, name='login'),
path('home/',views.home, name='home'),
path('add/',views.add, name="add"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
finally, the image never shows .. it is always an error in the link !!
Please note that image goes there in the static/media file after uploading, So i think it is some kind of URL error!
ERROR
The error is that the image always shows a broken link, and when I open the link (Open images link ) it gives me this error
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/media/documents/2018/05/18/test_dress3.jpg

You need to add MEDIA_URL to the project's urlpattern list:
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)
Check related part of the doc.

SOLVED
it was a wrong import reference, I used from django.conf.urls.static import static instead of from django.template.context_processors import static and it worked.

Related

Django url pattern is not a registered view function or pattern

I have a small Django web app, with multiple applications inside them. I have used the include in the urls.py files, but whenever I reference the URLs in the HTML files they don't load. Below are my 3 urls.py files. The one I'm having an issue will specifically is the nodes url pattern in the nodes urls.py
#main urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('account/', include('account.urls')),
]
#account urls.py
from django.urls import path, include
from django.contrib.auth import views as auth_views
from . import views
app_name = 'account'
urlpatterns = [
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
path('dashboard/', views.dashboard, name='dashboard'),
path('nodes/', include('nodes.urls')),
]
#nodes urls.py
from django.urls import path
from . import views
app_name = 'nodes'
urlpatterns = [
path('', views.nodes, name='nodes'),
]
This is my HTML file where I am referencing the URL pattern:
<li {% if section == 'nodes' %}class="active"{% endif %}>
<a class="nav-link" href="{% url 'nodes' %}">Nodes</a>
</li>
Due to this pattern name you set in urls file if change HTML file to this it must be fixed:
<li {% if section == 'nodes' %}class="active"{% endif %}>
<a class="nav-link" href="{% url 'account:nodes:nodes' %}">Nodes</a>
</li>
just for tips :) if import urls file at the django shell and print list of urlspatterns you could see default name assign to your nodes path.

Cannot Get image From Database Django Framework

I want to create a setting in admin panel which will help me to change the website logo from the admin panel. I create a model for database and it's working and uploading an image to the database + folder. but I cannot get this image to the Website template. when I'm viewing page source image SCR is empty.
my Model.py
class WebLogo(models.Model):
Logotitle = models.CharField(max_length=50,unique=False)
SiteLogo = models.ImageField(upload_to='webimages')
def __str__(self):
return self.Logotitle
my Views.py
from .models import Post,WebLogo
def Display_WebLogo(request):
# getting all the objects of hotel.
WebsiteLogo = WebLogo.objects.all()
return render((request, 'index.html',{'web_images' : WebsiteLogo}))
my project Urls.py
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
my Html Code
<a href="index.html"><img src="{{ WebLogo.SiteLogo.url }}" class="img-fluid" alt="logo">
</a>
my app url
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
]
In HTML Code, use 'web_images' not WebLogo like this
<a href="index.html"><img src="{{ web_images.0.SiteLogo.url }}" class="img-fluid" alt="logo">
</a>
It looks like {{ data.0 }}. See Variables and lookups.
You should write the required information in the settings.py file.
https://docs.djangoproject.com/en/dev/ref/settings/#media-root

NoReverseMatch at /polls/top/ 'polls' is not a registered namespace

Parent app name is mysite,child app name is polls.
I wrote in views.py
from django.shortcuts import render
from .models import Polls
def top(request):
data = Polls.objects.order_by('-created_at')
return render(request,'index.html',{'data':data})
def detail(request):
data = Polls.objects.order_by('-created_at')
return render(request,'detail.html',{'data':data})
in child app's urls.py
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns=[
url('top/', views.top, name='top'),
url('detail/<int:pk>/', views.top,name='detail'),
]
in parent app's urls.py
from django.contrib import admin
from django.conf.urls import url,include
app_name = 'polls'
urlpatterns = [
url('admin/', admin.site.urls),
url('polls/', include('polls.urls')),
]
in index.html
<main>
{% for item in data %}
<h2>{{ item.title }}</h2>
<a href="{% url 'polls:detail' item.pk %}">SHOW DETAIL
</a>
{% endfor %}
</main>
When I access top method, NoReverseMatch at /polls/top/
'polls' is not a registered namespace error happens.I am using Django 2.0,so I think namespace cannot used.I wrote app_name ,so I really cannot understand why this error happens.How should I fix this?What is wrong in my code?
The var app_name should be inside polls.urls not in the urls.py parent's file. Also if you want to use the new routing that Django provides remember add the path module:
from django.urls import path
path('detail/<int:pk>/', views.top,name='detail'),
If you're using the url module check this and be careful with what version you're using https://docs.djangoproject.com/en/2.0/topics/http/urls/

Django object.image.url not displaying even though path is correct

I have images I uploaded through django admin, but they are not displaying. The weird thing is that I have another project with the EXACT same code and it works. object.image.url outputs /media/media/image.jpg as does my other project. But this project does not show the image. if I put an image from my static folder or if I hardcode an image, it works fine. The problem is only when I try an image uploaded from the admin it does not work. Am I missing something in my settings.py file? or anywhere?
Models.py:
from django.db import models
# Create your models here.
class Connect(models.Model):
title = models.CharField(max_length=70)
short_description = models.TextField(null=True, blank=True)
description = models.TextField()
image = models.ImageField(upload_to='media', blank=True, null=True)
def __str__(self):
return self.title
views.py:
def index(request):
about = About.objects.all()
staff = Staffmembers.objects.all()
ministries = Ministries.objects.all()
connect = Connect.objects.all()
context = {
'template': 'home',
'connect': connect,
'about': about,
'staff': staff,
'ministries': ministries,
}
return render(request,'home/index.html', context)
template(index.html):
<div class="connect-wrapper row">
<h1 class="title connect-title">Connect</h1>
{% for object in connect %}
<div class="home-div connect-div col-md-4">
<h4>{{ object.title }}</h4>
<p>{{ object.short_description }}</p>
{% if object.image %}
<img class="connect-image-home" src="{{object.image.url}}" alt="connect">
<p>{{object.image.url}}</p> //sanity check
{% endif %}
</div>
{% endfor %}
</div>
settings.py:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
urls.py:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('home.urls'), name="home"),
]
I believe you need to add the media urls to your urls.py. Something like:
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('home.urls'), name="home"),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
On production environment Django does not load the media root automatically so that we can we can overcome that issue by adding following after url patterns:
urlpatterns = [
''''
your urls
''''
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
If you are using more than one app and including app urls on main app url, just add this on main project url.

How to render Image on the web page using path from DB in Django?

So I am trying to display an image on the web page, i save the image path in the database as media/imagename and in my html page i am doing this :
{% for stuff in profile %}
<div class="alert alert-success" role="alert"> {{ stuff.text }} </div>
<img scr='/Users/Username/PycharmProjects/social-django-1.9/mysite/media/media/{{ stuff.thumbnail }}' width="200">
{% endfor %}
And in my settings.py i do this:
MEDIA_ROOT = os.path.join(PROJECT_ROOT, '/Users/Username/PycharmProjects/social-django-1.9/mysite/media/media')
But the image doesn't display. What am i doing wrong here? Thanks!
Edit:
#urls.py
from django.conf.urls import patterns, url
from django.conf import settings
from social import views
urlpatterns = [
# main page
url(r'^$', views.index, name='index'),
# signup page
url(r'^signup/$', views.signup, name='signup'),
# register new user
url(r'^register/$', views.register, name='register'),
# login page
url(r'^login/$', views.login, name='login'),
# user doesnt exist webpage
url(r'^user-doesnt-exist/$', views.login, name='user-doesnt-exist'),
#page to show that the password is incorrect
url(r'^wrongpass/$', views.login, name='wrongpass'),
#webpage to show an error when a user tries to input nothing in the fields when signing up
url(r'^novalues/$', views.register, name='novalues'),
# logout page
url(r'^logout/$', views.logout, name='logout'),
# members page
url(r'^members/$', views.members, name='members'),
#invites page
url(r'^invites/$', views.invites, name='invites'),
# friends page
url(r'^friends/$', views.friends, name='friends'),
# user profile edit page
url(r'^profile/$', views.profile, name='profile'),
# messages page
url(r'^messages/$', views.messages, name='messages'),
# Ajax: check if user exists
url(r'^checkuser/$', views.checkuser, name='checkuser'),
#commiting again
]
if settings.DEBUG:
urlpatterns += patterns(''(r'^media/(P<path>.*)$','django.views.static.serve',
{'document_root':settings.MEDIA_ROOT,'show_indexes':True})),
Try setting your MEDIA_ROOT to:
MEDIA_ROOT = os.path.join(BASE_DIR, 'social/static/social/media')
MEDIA_URL = '/media/'
And in your project urls.py file add:
from django.conf import settings
from django.conf.urls import patterns
if settings.DEBUG:
urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}))
Then, in your template call the image like:
{% if stuff.thumbnail %}
<img src="{{ object.thumbnail.url }}">
{% endif %}
And in models.py:
image = models.ImageField(upload_to='images/')
Here's some great documentation on serving media files, including how to serve them during development.

Categories