I'm making a photo app using this light bird tutorial .
The problem is , The pictures that I upload . Won't display on the page.
I have never displayed a picture in django before and I think the problem is with the configuration
My models.py
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
from string import join
import os
from PIL import Image as PImage
from mysite.settings import MEDIA_ROOT
class Album(models.Model):
title = models.CharField(max_length=60)
public = models.BooleanField(default=False)
def __unicode__(self):
return self.title
def images(self):
lst = [x.image.name for x in self.image_set.all()]
lst = ["<a href='/media/%s'>%s</a>" % (x, x.split('/')[-1]) for x in lst]
return join(lst, ', ')
images.allow_tags = True
class Tag(models.Model):
tag = models.CharField(max_length=50)
def __unicode__(self):
return self.tag
class Image(models.Model):
title = models.CharField(max_length=60, blank=True, null=True)
image = models.FileField(upload_to="images/")
tags = models.ManyToManyField(Tag, blank=True)
albums = models.ManyToManyField(Album, blank=True)
created = models.DateTimeField(auto_now_add=True)
rating = models.IntegerField(default=50)
width = models.IntegerField(blank=True, null=True)
height = models.IntegerField(blank=True, null=True)
user = models.ForeignKey(User, null=True, blank=True)
def save(self, *args, **kwargs):
"""Save image dimensions."""
super(Image, self).save(*args, **kwargs)
im = PImage.open(os.path.join(MEDIA_ROOT, self.image.name))
self.width, self.height = im.size
super(Image, self).save(*args, ** kwargs)
def size(self):
"""Image size."""
return "%s x %s" % (self.width, self.height)
def __unicode__(self):
return self.image.name
def tags_(self):
lst = [x[1] for x in self.tags.values_list()]
return str(join(lst, ', '))
def albums_(self):
lst = [x[1] for x in self.albums.values_list()]
return str(join(lst, ', '))
def thumbnail(self):
return """<img border="0" alt="" src="/media/%s" height="40" />""" % (
(self.image.name, self.image.name))
thumbnail.allow_tags = True
def __unicode__(self):
return self.image.name
class AlbumAdmin(admin.ModelAdmin):
search_fields = ["title"]
list_display = ["title"]
My views.py
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.contrib.auth.decorators import login_required
from django.core.context_processors import csrf
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.forms import ModelForm
from mysite.settings import MEDIA_URL
from photo.models import *
def main(request):
"""Main listing."""
albums = Album.objects.all()
if not request.user.is_authenticated():
albums = albums.filter(public=True)
paginator = Paginator(albums, 10)
try: page = int(request.GET.get("page", '1'))
except ValueError: page = 1
try:
albums = paginator.page(page)
except (InvalidPage, EmptyPage):
albums = paginator.page(paginator.num_pages)
for album in albums.object_list:
album.images = album.image_set.all()[:4]
return render_to_response("photo/list.html", dict(albums=albums, user=request.user,
media_url=MEDIA_URL))
class TagAdmin(admin.ModelAdmin):
list_display = ["tag"]
class ImageAdmin(admin.ModelAdmin):
search_fields = ["title"]
list_display = ["__unicode__", "title", "user", "rating", "size", "tags_", "albums_",
"thumbnail", "created"]
list_filter = ["tags", "albums", "user"]
def save_model(self, request, obj, form, change):
obj.user = request.user
obj.save()
admin.site.register(Album, AlbumAdmin)
admin.site.register(Tag, TagAdmin)
admin.site.register(Image, ImageAdmin)
Ok here's the problem why the picture didn't show. You call the incorrect and override the path of the image. Remember you have already put function in your model the thumbnail so in your template you must put only:
<ul>
{% for album in albums.object_list %}
<div class="title">{{ album.title }} ({{ album.image_set.count }} images)</div>
<ul>
{% for img in album.images %}
{{img.thumbnail}}
{% endfor %}
</ul>
{% endfor %}
</ul>
This is correct but my problem is when I test it, the allow tags function has no effect so the output is a link instead of image. So I modified it and got the images show.
{% for img in album.images %}
<a href="{{MEDIA_URL}}{{ img.image}}">
<img border="0" alt="" src="{{MEDIA_URL}}{{ img.image}}" />
</a>
{% endfor %}
Related
I want to filter apartments by selecting subcity field in a dropdown in my django app. I'm using django-filters and django-bootstrap-form. But the dropdown does not populate with database querysets. How can I make the dropdown work?
models.py:
from django.contrib.sites.models import Site
from django.contrib.gis.db import models
from django.utils.crypto import get_random_string
from django.contrib.gis.geos import GEOSGeometry,Point
from django.contrib.auth.models import AbstractUser
from django.shortcuts import render
from django.urls import reverse
from django.forms import ModelForm
from django.template.defaultfilters import slugify
import datetime
from leaflet.forms.widgets import LeafletWidget
from django.contrib.gis.db import models as geo_models
# Create your models here.
class User(AbstractUser):
pass
geos_pnt=Point(4314498.56, 1003834.600,srid=3857)
#pnt=GEOSGeometry('POINT(4314498.56, 1003834.600)').wkt
class Apartment(models.Model):
ADKT='Addis Ketema'
AKLT='Akaki-Kality'
ARDA= 'Arada'
BOLE='Bole'
GLLE='Gulele'
KLFE='Kolfe-Keranio'
KIRK='Kirkos'
LDTA='Lideta'
YEKA='Yeka'
NFSL='Nefas Silk-Lafto'
SUBCITY_CHOICES = [
(ADKT, 'Addis Ketema'),
(AKLT, 'Akaki-Kality'),
(ARDA, 'Arada'),
(BOLE, 'Bole'),
(GLLE, 'Gulele'),
(KLFE, 'Kolfe-Keranio'),
(KIRK,'Kirkos'),
(LDTA, 'Lideta'),
(NFSL, 'Nefas Silk-Lafto'),
(YEKA, 'Yeka')]
apt_id = models.CharField(max_length=200, primary_key=True,editable=True)
geom = geo_models.PointField(null=True)
apt_area = models.IntegerField(default=0, null=True)
no_bedrooms = models.IntegerField(null=True)
apt_cost = models.IntegerField(default=0, null=True)
apt_subcity = models.CharField(default='KIRK',choices=SUBCITY_CHOICES,max_length=30,null=True)
register_date = models.DateTimeField(auto_now_add=True,null=True)
objects = models.Manager()
sites =models.ManyToManyField(Site)
#change points from apt_rent_db to kml
def pointkml(self):
points = Apartment.objects.kml()
return render("placemarks.kml", {'places': points})
def get_absolute_url(self):
return reverse('rent_app:apartment-listing', kwargs={'pk': self.pk})
def save(self, *args, **kwargs):
#self.Latitude = self..y
#self.Longitude = self.location.x
self.slug = slugify(self.apt_id)
super(Apartment, self).save(*args, **kwargs)
class Meta:
# order of drop-down list items
verbose_name = ("Apartment")
verbose_name_plural = ("Apartments")
ordering = ('apt_cost',)
app_label = 'rent_app'
def __unicode__(self):
return self.apt_id
#property
def picture_url(self):
return self.picture.url
class UserProfile(models.Model):
first_name = models.CharField(max_length=100, null=False)
last_name = models.CharField(max_length=100,null=False)
gender = models.CharField(max_length=100)
phone_no = models.CharField(max_length=12)
sites = models.ManyToManyField(Site)
views.py:
class ApartmentFilterView(FilterView):
model = Apartment
context_object_name = 'apartments'
filter_class = ApartmentFilter
filters.py:
import django_filters
from .models import Apartment,UserProfile
class ApartmentFilter(django_filters.FilterSet):
ADKT = 'Addis Ketema'
AKLT = 'Akaki-Kality'
ARDA = 'Arada'
BOLE = 'Bole'
GLLE = 'Gulele'
KLFE = 'Kolfe-Keranio'
KIRK = 'Kirkos'
LDTA = 'Lideta'
YEKA = 'Yeka'
NFSL = 'Nefas Silk-Lafto'
SUBCITY_CHOICES = [
(ADKT, 'Addis Ketema'),
(AKLT, 'Akaki-Kality'),
(ARDA, 'Arada'),
(BOLE, 'Bole'),
(GLLE, 'Gulele'),
(KLFE, 'Kolfe-Keranio'),
(KIRK, 'Kirkos'),
(LDTA, 'Lideta'),
(NFSL, 'Nefas Silk-Lafto'),
(YEKA, 'Yeka')]
ordering = django_filters.ChoiceFilter(label='Ordering',subcity_choices=SUBCITY_CHOICES, method='filter_by_ordering')
class Meta:
model = Apartment
fields = {
'apt_cost': ['lte'],
#'apt_dist': ['lt'],
'apt_subcity': ['icontains'],
}
template:
{% extends 'base.html' %}
{% load bootstrap %}
{% block title %} የተገኙ ቤቶች | Apartment List {% endblock title %}
{% block content %}
<form action="" method="get">
{{ filter.form.as_p }}
<input type="submit">
</form>
{% for obj in filter.qs %}
{{obj.apt_id}} - Birr {{obj.apt_cost}}
{% endfor %}
{% endblock %}
Your model should be listed in the Meta class.
class yourfilter(django_filters.FilterSet):
class Meta:
model = your_model
i want to show image from model.py file in user app where i uplode my image.
this is user.model.py file
model.py
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to = 'profile_pics')
def __str__(self):
return f'{self.user.username} profile.'
def save(self):
super().save()
img = Image.open(self.image.path)
if img.height>300 or img.width > 300:
img.thumbnail( (300,300) )
img.save(self.image.path)
blog.model.py(blog is another app) .
this is blog.model.py file
model.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100,help_text="enter within 100 charecter")
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
# this is for show demo form admin site (if you use this than genarate a button for demo )
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk' : self.pk})
And this is my class base view funcatin in blog app Whose template name is home.html.
this is blog.view.py file
view.py
class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 5
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['ip'] = self.request.session.get('ip', 0)
return context
home.html
I show you only image tag.
{% for post in posts %}
<img style="height: 80px; width: 80px; float: left;" class=" img-circle account-img " src="{{ post.author.profile.image.url }}">
{% endfor %}
What i write code in template this is doesn't show image.
THis is my home.html page [click]1
I need to show image from user.model.py file where image is tabel row in home.html file.
If you want anything plase tell me. thankyou....
So i have a model called folder, i want to show all the folder created by current user on HomeView, but somehow it's not working, what i think is that folders are not getting connected to user who created them.
models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE
from django.core.validators import MinValueValidator
from django.core.exceptions import PermissionDenied
# The Folders Model.
class Folder(models.Model):
name = models.CharField(max_length = 250)
parent = models.ForeignKey('self', on_delete = CASCADE, null = True, blank = True )
cr_date = models.DateTimeField(auto_now_add = True)
user = models.OneToOneField(to=User, on_delete=CASCADE, null=True, blank=True)
def __str__(self):
return "%s" % self.name
view.py
class HomeView(TemplateView):
template_name = "ahmed_drive/home.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user = self.request.user
home_folders = Folder.objects.filter(user=user).order_by('-cr_date')
home_files = Fileshare.objects.filter(uploaded_by=user).order_by('-id')
context['home_folders'] = home_folders
context['home_files'] = home_files
return context
#method_decorator(login_required, name="dispatch")
class FolderCreate(CreateView):
model = Folder
fields = ["name", "parent"]
def formvalid():
if form.is_valid():
form.save()
return redirect('home.html')
else :
return render(request,{'form': form})
home.html
{% extends 'base.html' %}
{% block content %}
{% for Folder in home_folders %}
<h1> {{Folder.name}} </h1>
{% endfor %}
{% endblock %}
when you create folder you don't connect user to it.
you need to do it before saving form
def form_valid(self, form):
folder = form.save(commit=False)
folder.user = request.user
folder.save()
return redirect('home.html')
I can`t correctly include "mainslider.html" in my index.html as
{% include "pages/mainslider.html" %}
my index page views:
from django.shortcuts import render_to_response
def index(request):
return render_to_response('index.html')
i can see my slider at http://127.0.0.1:8000/slider/ , but nothing http://127.0.0.1:8000/
it is slider code:
models.py
from django.db import models
from ckeditor.fields import RichTextField
from easy_thumbnails.fields import ThumbnailerImageField
class Portfolio(models.Model):
title = models.CharField(max_length = 200)
description = models.TextField(max_length = 500)
meta_desc = models.CharField(max_length=200)
meta_key = models.CharField(max_length=200)
device = RichTextField()
image = ThumbnailerImageField( upload_to = 'media')
def __unicode__(self):
return self.title
def get_absolute_url(self):
return "/works/%i/" % self.id
class Slider(models.Model):
title = models.CharField( max_length = 500)
image = ThumbnailerImageField( upload_to = 'media')
whichslide = models.ForeignKey('Portfolio')
def __unicode__(self):
return self.title
views.py
class SliderListView(ListView):
model = Slider
context_object_name = 'sliders'
template_name = 'pages/mainslider.html'
def get_context_data(self, **kwargs):
context = super(SliderListView, self).get_context_data(**kwargs)
context['portfolio'] = Portfolio.objects.all()
return context
mainslider.html
<ul class="rslides" id="slider">
{% for slider in sliders %}
<li>
<img src="{{ slider.image.mainslider.url }}" alt="{{ slider.whichslide.title }}">
<p class="caption">{{ slider.title }}</p>
</li>
{% endfor %}
</ul>
and some urls.py:
url(r'^slider/$', SliderListView.as_view(), name="slider_list"),
Like #Simein Visser said, you have to include the data in the index view.
One simple solution could be use that instead your index function:
class Index(SliderListView):
# you're reusing the context data included by SliderListView view
template_name = 'index.html'
I'm trying to subclass the YearArchiveView class-based view to show a list of articles published in a year, but the filtering doesn't work and example.com/2012 shows articles from all years.
Note that I do not want the view code in urls.py. Rather, I want the LogbookYearArchive wrapper to continue living in views.py.
models.py:
class Entry(models.Model):
KIND = (
('L', 'Link'),
('A', 'Article'),
)
title = models.CharField(max_length=200)
slug = models.SlugField(unique_for_date='pub_date')
kind = models.CharField(max_length=1, choices=KIND, default=1,
help_text="Is this a link to other content or an original article?")
url = models.URLField(blank=True, help_text="The link URL")
body = models.TextField(blank=True)
body_html = models.TextField()
content_format = models.CharField(choices=CONTENT_FORMAT_CHOICES,
max_length=50, default=1)
is_active = models.BooleanField(help_text=_("Tick to make this entry\
live (see also the publication date). Note that administrators\
(like yourself) are allowed to preview inactive entries whereas\
the general public aren't."), default=True)
pub_date = models.DateTimeField(verbose_name=_("Publication date"),
help_text=_("For an entry to be published, it must be active and its\
publication date must be in the past."))
mod_date = models.DateTimeField(auto_now_add=True, editable=False)
class Meta:
db_table = 'blog_entries'
verbose_name_plural = 'entries'
ordering = ('-mod_date',)
get_latest_by = 'pub_date'
def __unicode__(self):
return self.title
#models.permalink
def get_absolute_url(self):
"""Construct the absolute URL for an Entry of kind == Article."""
return ('logbook-entry-detail', (), {
'year': self.pub_date.strftime("%Y"),
'month': self.pub_date.strftime("%m"),
'slug': self.slug})
urls.py:
from __future__ import absolute_import
from django.conf.urls import patterns, include, url
from .models import Entry
from .views import LogbookYearArchive
urlpatterns = patterns('',
url(r'^(?P<year>\d+)/$',
view=LogbookYearArchive.as_view(),
name='archive-year'),
)
views.py:
from django.views.generic.list import MultipleObjectMixin
from django.views.generic import ArchiveIndexView, MonthArchiveView, YearArchiveView, DetailView
from django.core.urlresolvers import reverse
from .models import Entry
class LogbookYearArchive(YearArchiveView):
"""Yearly archives of articles"""
model = Entry
date_field = 'pub_date'
year_format='%Y'
make_object_list=True,
template_name = 'hth/archive_year.html'
allow_future = False
def get_context_data(self, **kwargs):
context = super(LogbookYearArchive, self).get_context_data(**kwargs)
# =todo: fix filtering by date which is not working
context['object_list'] = Entry.objects.filter(
is_active=True, kind='A').order_by('-pub_date', 'title')[:9999]
return context
archive_year.html:
{% block content %}
<h1 style="margin-bottom:1em;">Articles Published in {{ year|date:"Y" }}</h1>
{% for object in object_list %}
{% ifchanged %}
<h2 class="dateline datelinearchive">{{ object.pub_date|date:"F Y" }}</h2>
{% endifchanged %}
<p>
{{ object.title }}
</p>
{% endfor %}
{% endblock %}
Can you try this:
class LogbookYearArchive(YearArchiveView):
"""Yearly archives of articles"""
model = Entry
date_field = 'pub_date'
year_format='%Y'
make_object_list=True,
template_name = 'hth/archive_year.html'
allow_future = False
queryset = Entry.objects.filter(
is_active=True, kind='A').order_by('-pub_date', 'title')
I added a queryset attribute and removed get_context_data()
I had the same problem. All ArchiveViews were working except YearArchiveView. Solution was found in make_object_list property. It should be True
That's a cut from django code
if not self.get_make_object_list():
# We need this to be a queryset since parent classes introspect it
# to find information about the model.
qs = qs.none()