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 }}
Related
hi when i am saving images from my admin they are saved in project directory like this images/images/myimg.jpg.. but when i am trying to display them in my template like this
<img src="{{About.image.url}}" alt="profile photo">
the image do not displays.. when i inspect the page in chrome... it shows image source unknown..
<img src="(unknown)" alt="profile photo">
please see the files ..
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS =[
os.path.join(BASE_DIR,'portfolio/static')
]
STATIC_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL ='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'images')
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/', admin.site.urls),
path('home/', include("home.urls")),
path('blog/', include("blog.urls")),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT )
the model having image is inside a app named 'home'
models.py of home app
from django.db import models
import datetime
# Create your models here.
class About(models.Model):
image = models.ImageField(upload_to = 'images')
desc = models.TextField()
home/views.py
from django.shortcuts import render
from home.models import *
from django.views.generic import ListView
# Create your views here.
def index(request):
abt = About.objects.all()
return render(request,'home/index.html',{'abt': abt.first()})
def Experience(request):
Exp = Experience.objects.all()
return render(request,'home/Experience.html',{'Exp': Exp})
class MyView(ListView):
context_object_name = 'name'
template_name = 'home/index.html'
queryset = About.objects.all()
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
context['Experience'] = Experience.objects.all()
context['Education'] = Education.objects.all()
context['Award'] = Award.objects.all()
context['Membership'] = Membership.objects.all()
context['About'] = self.queryset
return context
if about you're passing queryset so try looping them and accessing each image
{% for data in About %}
<img src="{{data.image.url}}" alt="profile photo">
{% endfor %}
I just started with a Django project using django-allauth, I configured the basic settings, without using any 3rd party provider. I have set up the urls.py of my project and urls.py of my app.
But on going to http://localhost:8000, I am getting to 'home.html' but how do I remove the navigation of allauth
The following is the urls.py of my project :
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('ckeditor/',include('ckeditor_uploader.urls')),
path('',include('blog.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
And this my urls.py of app :
from django.urls import path, include
from . import views
urlpatterns = [
path("", views.PostListView.as_view(), name = 'post_list'),
path("post/add", views.CreatePostView.as_view(), name = "create_new_post"),
]
views.py
from django.shortcuts import render
from django.views.generic import ListView, View
# Create your views here.
from .forms import PostForm, CommentForm
from .models import Post, Comment
class PostListView(ListView):
queryset = Post.objects.filter(is_published=True)
template_name = 'home.html'
class CreatePostView(View):
form_class = PostForm()
template_name = 'create_post.html'
model = Post
home.html
{% extends 'base.html' %}
{% block content %}
<h1>Hello World</h1>
{% for post in post_list %}
<h1>{{post.post_title}}</h1>
<p>{{post.post_body|safe}}</p>
{% endfor %}
{% endblock %}
path("post/add/", views.CreatePostView.as_view(), name = "create_new_post"),
add trailing slash to your url
your global urls.py:
path('',include('blog.urls')),
add something in your app urls.py:
path('test/',views.PostListView.as_view()),
after adding this to your urls.py, run your app again
the extended base.html file may contain the navigation. make changes there to remove or simply remove it
{% extends 'base.html' %}
within an app I have two models, named Course and Step. Every Step belongs to a Course and each Course has many steps. However, I'm having problem creating a detailview for Steps. For example when i go to the url 'http://127.0.0.1:8000/courses/1' it should display steps for course.objects.get(pk=1). However what i get back is just the page for course, i.e, http://127.0.0.1:8000/courses'.
Model
from django.db import models
# Create your models here.
class Course(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length= 255)
description = models.TextField()
def __str__(self):
return self.title
class Step(models.Model):
title = models.CharField(max_length = 255)
description = models.TextField()
order = models.IntegerField()
course = models.ForeignKey(Course)
def __str__(self):
return self.title
Url
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.course_list),
url(r'(?P<pk>\d+)/$', views.course_detail)
]
View
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from .models import Course, Step
def course_list(request):
courses = Course.objects.all()
return render(request, 'courses/course_list.html', {'courses': courses})
def course_detail(request, pk):
course = Course.objects.get(pk=pk)
return render(request, 'courses/course_detail.html', {'course': course})
course_detail.html
{% extends 'layout.html' %}
{% block title %}{{course.title}}{% endblock %}
{% block content %}
<article>
<h2>{{ course.title }} %</h2>
{{course.description}}
<section>
{% for step in course.step_set.all %}
<h3>{{ step.title }}</h3>
{{step.description}}
{% endfor %}
</section>
</article>
{% endblock %}
Main Urls
from django.conf.urls import url, include
from django.contrib import admin
from courses.views import course_list
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url(r'^courses/', course_list),
url(r'^admin/', admin.site.urls),
url(r'^$', views.hello_world),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I just can't seem to recognize where i went wrong
I think the you need these url mappings..! This should do the trick.
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^applicationName/$', views.ListView.as_view(), name='courses'),
url(r'^applicationName/(?P<pk>\d+)$', views.CourseDetailView.as_view(), name='course-detail'),
]
The problem is in your main urls.py file - this line makes any URL path starting with 'courses/' resolve to the course_list view:
url(r'^courses/', course_list),
So Django will never reach the course_detail view. Instead, you must "include" the application-specific URLs:
url(r'^courses/', include('myproject.myapp.urls'),
Where myproject is your main project name, and myapp is your app name (make sure you also registered your application under INSTALLED_APPS at your settings.py file).
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" />
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}