Imagefield in Django HTML Variable - python

I'm new to Django and trying to create a website with uploading image via Django Admin.
I'm trying to view image uploaded in Imagefield in my HTML.
But i just can't get the image working right.
Banner.objects.all() doesn't seems able to get all the image file located in media folder.
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('', include('blog.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
from django.db import models
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver
from django.utils import timezone
from django.contrib.auth.models import User
from PIL import Image
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now) #auto_now=True //auto date
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Banner(models.Model):
title = models.CharField(max_length=100)
images = models.ImageField(upload_to='images',null=True,blank=True)
def __str__(self):
return self.title
views.py
from django.shortcuts import render
from django.views.generic import(
ListView,
DetailView
)
from .models import *
# Create your views here.
class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted'] #arrange date posted with latest on top
paginate_by = 6
def Banner_view(request):
banner = Banner.objects.all()
return render(request, 'blog/home.html',{'banner':banner})
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
#uploaded file in base directory "media"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
home.html
{% for b in banner %}
<div>
<img src="{{ b.images.url }}">
</div>
{% endfor %}

you should have write this way
you should use / for path detect
images = models.ImageField(upload_to='images/', null=True,blank=True)

Related

How to store images using Django forms?

I'm new to django. I've been stuck for a while. I believe everything is configured correctly. However, when my objects are created it is not creating the media directory or storing the files/images. I have done the settings file, urls, views, models, forms everything.
Here are relevant files:
// setting.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
// models.py
class Trip(models.Model):
city = models.CharField(max_length= 255)
country = models.CharField(max_length= 255)
description = models.CharField(max_length= 255)
creator = models.ForeignKey(User, related_name = 'trips_uploaded',on_delete= CASCADE, null=True)
favoriter = models.ManyToManyField(User, related_name= 'fav_trips')
photo = models.ImageField(null=True, blank =True, upload_to='trips/')
// urls.py ( there were 2 ways to write media according to tutorial)
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('', include('travelsiteapp.urls'))
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
// views.py (lastly)
def tripAdd(request):
form = TripForm()
if request.method == 'POST':
form = TripForm(request.POST, request.FILES)
if form.is_valid():
form.photo = form.cleaned_data["photo"]
form.save()
context = { 'form': form}
return render(request, 'tripAdd.html', context)
// html/ form
<form action="/createTrip"method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="submit">
</form>
// forms.py
from django import forms
from django.forms import ModelForm
from .models import Trip
from django import forms
class TripForm(ModelForm):
class Meta:
model = Trip
fields = ['city', 'country', 'description', 'photo']
// I have hit all the steps not sure whats wrong? & and installed pip pillow
Which url is serving the tripAdd() view? If it is /createTrip as in your form, then add a trailling slash in the action like this: /createTrip/. When you post to an URL, Django expects a trailing slash by default. You can customize that behavior if you like. Also, don't forget to declare this URL (since it is not in the example you provided).

Django display Image of User

Good Day,
every user has an image, how can I display the specific user image?
\\models.py
class UserImage(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE)
photo = models.ImageField(
upload_to='images/', height_field=None, width_field=None, max_length=100)
def __str__(self):
return str(self.user)
\\forms.py
class UserImageForm(forms.ModelForm):
class Meta:
model = UserImage
fields = (
'photo',
)
\\views.py
def photo_view(request):
try:
profile = request.user.userimage
except UserImage.DoesNotExist:
profile = UserImage(user=request.user)
if request.method == 'POST':
form = UserImageForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
form.save()
return redirect('/dashboard/user/photo')
else:
form = UserImageForm(instance=profile)
return render(request, 'photo.html', {'form': form, 'profile': profile})
test.html
<img src="{{ WhatHere? }}" alt="User Profile Image" />
So in src="" must be the URL to the image what the user has added. Each user can only see his own image, not all existing images should be displayed.
EDIT
\\settings.py
LOGIN_URL = '/signin'
LOGIN_REDIRECT_URL = '/signin'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
\\ urls.py
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from abstractuser.views import (
signup_view,
signin_view,
signout_view,
)
from dashboard.views import (
dashboard_home_view,
title_delete,
profile_view,
photo_view,
)
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('signup/', signup_view),
path('signin/', signin_view),
path('signout/', signout_view),
path('dashboard/home', dashboard_home_view),
path('dashboard/title/delete/<int:title_id>',
title_delete, name="delete_title"),
path('dashboard/user/profile/', profile_view),
path('dashboard/user/photo/', photo_view),
]
I think I have to add something to the urls.py but I have no idea what
You can use
<img src="{{ profile.photo.url }}" alt="User Profile Image" />
And in your settings.py you have to set MEDIA_URL and MEDIA_ROOT AS
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
And in your project's main urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('signup/', signup_view),
path('signin/', signin_view),
path('signout/', signout_view),
path('dashboard/home', dashboard_home_view),
path('dashboard/title/delete/<int:title_id>',
title_delete, name="delete_title"),
path('dashboard/user/profile/', profile_view),
path('dashboard/user/photo/', photo_view),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

images are not showing in django

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 %}

Unable to render Images in template

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" />

ImageField class in django 1.8 not displaying image in the template

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 }}

Categories

Resources