i'm learning to upload and display images in Django but I've run into a block where I can't figure out how to call the images location from the database and then display it in a template, i've uploaded image from admin panel and wants to display it in template...
models.py
from django.db import models
from time import time
class Couple(models.Model):
image_bride = models.ImageField(upload_to='vivaah/static/media')
image_groom = models.ImageField(upload_to='vivaah/static/media')
vivaah/views.py
def index(request, bride_first_name, groom_first_name):
obj = Couple.objects.get(bride_first_name__iexact=bride_first_name)
image_bride = obj.image_bride
image_groom = obj.image_groom
context = {'image_bride':image_bride, 'image_groom':image_groom}
return render(request, 'vivah/index.html', context)
templates/index.html
<img class="profile_pic" src="{{ image_bride.url }}"/>
vivaah/urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from . import views
import os
urlpatterns = [
url(r'^(?P<bride_first_name>[a-zA-Z]+)weds(?P<groom_first_name>[a-zA-Z]+)/$', views.index, name='index'),
]
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
import os
urlpatterns = [
url(r'^vivah/', include('vivaah.urls')),
url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media/')
it shows only borders of the image but not actual image
In your templates/index.html, you asking for url on couple object
<img class="profile_pic" src="{{ couple.image_bride.url }}"/> but couple is not passed to your template.
Change this line context = {'image_bride':image_bride, 'image_groom':image_groom}
to this context = {'couple': obj}
Related
I am new to Django and I was working at my first project, but I got:
NoReverseMatch with Exception Value: 'hiring_log_app' is not a
registered namespace in base.html
which follows:
href="{% url 'hiring_log_app:index' %}" >Hiring Log
href="{% url 'hiring_log_app:topics' %}" >Topics
I made sure my namespace was correct and I looked at the other topics already opened without figuring out how to solve the issue.
I paste urls.py:
from django.contrib import admin
from django.conf.urls import include, url
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'', include ('hiring_log_app.urls', namespace='hiring_log_app')),
hiring_log_app/urls.py:
"""Define URL patterns for hiring_log_app"""
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^topics/$', views.topics, name='topics'),
]
views.py:
from django.shortcuts import render
from .models import Topic
def index(request):
"""The home page for hiring_log_app"""
return render(request, 'hiring_log_app/index.html')
def topics(request):
""" list of topics"""
topics = Topic.objects.raw( "SELECT text FROM HIRING_LOG_APP_TOPIC;")
context = {'topics' : topics}
return render(request, 'hiring_log_app/topics.html', context)
Does anyone know where I am making a mistake?
You have wrongly specified the namespace in urlpatterns. Follow the pattern below:
from django.contrib import admin
from django.conf.urls import include, url
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'', include (('hiring_log_app.urls','hiring_log_app'), namespace='hiring_log_app'))
Edit:
If you are using Django 2.2.4 then you should use path instead of url since the usage of it is replaced by re_path.
from django.contrib import admin
from django.conf.urls import include
from django.urls import re_path
urlpatterns = [
re_path(r'^admin/', include(admin.site.urls)),
re_path(r'', include (('hiring_log_app.urls','hiring_log_app'), namespace='hiring_log_app'))
I installed Django in my server, after that i was able to see the "IT WORKED" page and the "Django administration" page (www.mydomain.com/admin).
I sync my Database (No problem with that), I collected my static files as well
The problem comes when I try to login into the administration page,
After I try to login with or without the correct username or password I get:
I checked my urls.py and didn't find anything out of the ordinary:
project/urls.py:
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import TemplateView
from app_belldent import views
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from sitio_belldent import settings
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.inicio, name="inicio"),
url(r'^servicios/$', views.servicios, name="servicios"),
url(r'^portafolio/$', views.portafolio, name="portafolio"),
url(r'^contactenos/$', views.contact, name="contactenos"),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
app/urls.py:
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.inicio),
url(r'^servicios/$', views.servicios, name="servicios"),
url(r'^portafolio/$', views.portafolio, name="portafolio"),
url(r'^contactenos/$', views.contact, name="contactenos"),
url(r'^inicio/$', views.inicio, name="inicio"),
url(r'^thanks/$', views.thanks, name='thanks'),
]
I am trying to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for gallery images with a filefield), the image is stored in /media/images correctly. I have my media settings set in settings.py as follows:
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
Project urls.py:
from django.conf.urls import include, url
from django.contrib import admin
import gallery.views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('gallery.urls')),
]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Gallery 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(r'^', views.homepage, name = 'home'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Gallery views.py:
def homepage(request):
texts = Sitetext.objects.all()
gal = Galleryimg.objects.all()
gal.order_by('position')
return render(request,'index.html', {"text1":texts[0].text,"text2":texts[1].text,"text3":texts[2].text,"text4":texts[3].text,"title1":texts[0].title,"title2":texts[1].title,"title3":texts[2].title,"title4":texts[3].title,"gallery":gal})
And then this is the part of the template code that accesses the image:
{% for g in gallery %}
<div class="col-md-3 col-sm-4 col-xs-6">
<img class="img-responsive" src="g.imgfile.url" />
</div>
{% endfor %}
When I create a gallery image, a broken image pops up, but the image is not accessed correctly.
I do this and I am able to serve media files from the Django development server:
urlpatterns += [
url(r'^media/(?P<path>.*)$', django.views.static.serve, {
'document_root': settings.MEDIA_ROOT}),]
It should be enough to include that just in the project urls.py.
The issue with yours could be that your media URL entry in urls.py is not correct. You seem to be not matching the actual URL of the media file, which is probably something like /media/something.png. You seem to be just qualifying on /media/. I also think your regex should be ^media/, not /media/.
Remove the static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) part, from your gallery.urls file.
Replace src="g.imgfile.url" with src="{{ g.imgfile.url }}".
Aside question: Why do you pass this big dictionary ({"text1":texts[0].text,...) to your template? It is error prone and bad practice. You should just pass 'texts': texts and inside your template iterate over them with a {% for text in texts %} forloop. So, the render method should be something like render(request, 'index.html', {'texts': texts, 'gallery': gal}).
I have tried so many things to fix this issue but still I can't get it to work.
I can't get my MEDIA images to render correctly in the template, although the url in the page source is the correct absolute path, still the images won't appear.
models.py
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
import os
class Contact(models.Model):
user = models.OneToOneField(User,null=True)
website = models.URLField(blank=True,null=True)
db = models.ImageField(upload_to=settings.MEDIA_ROOT)
def __unicode__(self) :
return unicode(self.user) or u''
views.py
from django.shortcuts import render
from .models import Contact
from django.contrib.auth.models import User
def user_page(request,user_name):
try :
user = User.objects.get(username=user_name)
except User.DoesNotExists :
return (request,'main.html')
return render(request,'main/user_page.html',{'user':user})
urls.py
from django.conf.urls import url
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
import views
urlpatterns = [
url(r'^(?P<user_name>\w+)/$',views.user_page , name = 'main_page'),
]
if settings.DEBUG :
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
main/user_page.html
{% load staticfiles %}
<h1>{{user.username}}</h1>
<img src="{{user.contact.db.url}}" alt="My image"/>
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root')
STATIC_DIR = (
os.path.join(PROJECT_DIR,'static'),
)
MEDIA_ROOT =os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
Thanks and sorry for the bad english
db = models.ImageField(upload_to=settings.MEDIA_ROOT)
Is wrong. Quote form documentation:
FileField.upload_to
A local filesystem path that will be
appended to your MEDIA_ROOT setting to determine the value of the url
attribute.
Thus:
db = models.ImageField(upload_to="foo")
Will upload to MEDIA_ROOT + "foo".
Try doing this instead:
models.py:
class Contact(models.Model):
user = models.OneToOneField(User,null=True)
website = models.URLField(blank=True,null=True)
db = models.ImageField(upload_to=some_folder_here)
def __unicode__(self) :
return unicode(self.user) or u''
def get_db_url(self):
return "{}{}".format(settings.MEDIA_URL, self.db)
views.py:
def user_page(request,user_name):
try :
user = User.objects.get(username=user_name)
photo = Contact.objects.filter(user=user)
except User.DoesNotExists :
return (request,'main.html')
context = {
'user': user',
'photo': photo
}
return render(request,'main/user_page.html', context)
html:
{% load staticfiles %}
<img src="{{ photo.get_db_url }}" alt="My image" />
According to the code the image should be displayed on the index.html template but there seems to be some problem with the img src
My models.py
from django.db import models
class Rockinfo(models.Model):
rock_name = models.CharField(max_length=200,default="ac/dc")
rock_img = models.ImageField(upload_to="%Y/%m/%d",default="1992/08/92")
rank = models.IntegerField(default=0)
def __str__(self):
return self.rock_name
My admin.py
from django.contrib import admin
from .models import Rockinfo, Rockvids
class ChoiceInline(admin.TabularInline):
model = Rockvids
extra = 10
class RockinfoAdmin(admin.ModelAdmin):
fieldsets = [
('The Fucking Band', {'fields': ['rock_name']}),
('Image', {'fields': ['rock_img']}),
]
inlines = [ChoiceInline]
list_display = ('rock_name', 'rock_img')
list_filter = ['rank']
search_fields = ['rock_name']
admin.site.register(Rockinfo, RockinfoAdmin)
my application's urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
]
My project's models.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^rockinglist/', include('rockinglist.urls', namespace="rockinglist")),
url(r'^admin/', include(admin.site.urls)),
]
My views.py file
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from .models import Rockvids, Rockinfo
class IndexView(generic.ListView):
template_name = 'rockinglist/index.html'
context_object_name = 'latest_rockinfo_list'
def get_queryset(self):
return Rockinfo.objects.order_by('-rank')[:5]
The index.html file
{% if latest_rockinfo_list %}
<ul>
{% for rockinfo in latest_rockinfo_list %}
<h1>{{ rockinfo.rock_name }}</a></li>
<img src="img\{{ rockinfo.rock_img }}" alt="ac/dc">
{% endfor %}
</ul>
{% else %}
<p>No</p>
{% endif %}
I think the problem is with the root of the image.Somehow django cannot reach the images.I want to display the rock_name along with the associated rock_img. Can someone help me figure this out.Thanks in advance.
In your project's urls.py, add this:
# your other imports here ...
# ...
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLs ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In your settings.py file, make sure you have this:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
In your templates:
<img src="{{ rockinfo.rock_img.url }}" alt="ac/dc">
Note: If BASE_DIR is not defined in your settings, put this on top of your settings file:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
First of all check if MEDIA_URL is provided in you settings. Django doesn't server media during development so you have to have the following in your project's urls.py:
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)
after this you can access your image in template with
{{ rockinfo.rock_img.url }}