Error when using django-admin-multiupload and django-imagekit together - python

At the moment I'm on my way using the django-imagekit to show thumbnails in an image-heavy view of a gallery app. For this purpose I'm using the 'model-method', means I'm creating the thumbnails within the model.
Now with the comfort of the admin in mind (upload multiple picture at once) I also want to implement a multi-upload form in the admin-view. To ease things a little bit I tried to use an app I found on GitHub, django-admin-multiupload (I'm not able to link to it because of my low reputations but that's the exact name for it on GitHub).
When I only use django-imagekit, everything works fine and I get nice thumbnails, just like expected. When I only use django-admin-multiupload, everything works fine and I'm able to upload multiple images just like expected.
The problem starts when I'm using both apps at the same time. The multiupload works still fine but when I'm opening the view, and actually implementing the thumbnail (only using both and not implementing the thumbnail works fine), where the thumbnails should be shown I will get the following error:
OSError at /gallery/ - decoder jpeg not available
You can see the full error here: http://pastebin.com/gtVYEeG7
My confusion starts when starting only the single app and it works. So as far as my knowledge goes, all PIL issues could not be present.
To provide some more information: I'm using a virtualENV with the following list of packages:
pip
django
PIL
pilkit
django-imagekit
django-amdin-multiupload
To also provide some of my implementet code, here it is:
File: models.py
class Image(models.Model):
"""the model for the images"""
# the foreign key from the event
event = models.ForeignKey('Event', related_name='images',
blank=True, null=True)
# the image itself
# file = models.FileField('File', upload_to='gallery/images/')
file = models.ImageField('File', upload_to='gallery/images/')
image_thumbnail = ImageSpecField(source='file',
processors=[
ResizeToFill(300, 250)
],
format='JPEG',
options={'quality': 40})
# image title to represent it in the admin interface
image_name = models.CharField(max_length=35, default='img')
# publication date of the image
pub_date = models.DateTimeField('date published',
auto_now_add=True)
# for a better representation of the image
def __str__(self):
return self.image_name
File: admin.py
(this one is mostly as suggested in the example from the django-admin-multiupload repo, can be viewed here: https://github.com/gkuhn1/django-admin-multiupload/blob/master/example/gallery/admin.py)
from django.contrib import admin
from django.shortcuts import get_object_or_404
from gallery.models import Event, Image
from multiupload.admin import MultiUploadAdmin
# Register your models here.
# allows inline add of single images
class ImageInlineAdmin(admin.TabularInline):
model = Image
# used to define the process_uploaded_file function
# so it will not be duplicated in the Admin-Classes
class GalleryMultiuploadMixing(object):
def process_uploaded_file(self, uploaded, event, request):
image = event.images.create(file=uploaded)
return {
'url': image.file.url,
'thumbnail': image.file.url,
'id': image.id,
'name': image.image_name
}
# admin class for event model
class EventAdmin(GalleryMultiuploadMixing, MultiUploadAdmin):
inlines = [ImageInlineAdmin,]
multiupload_form = True
multiupload_list = False
def delete_file(self, pk, request):
obj = get_object_or_404(Image, pk=pk)
return obj.delete()
admin.site.register(Event, EventAdmin)
# admin class for image model
class ImageAdmin(GalleryMultiuploadMixing, MultiUploadAdmin):
multiupload_form = False
multiupload_list = True
admin.site.register(Image, ImageAdmin)
File: index.html
<td><img class="img-responsive" src="{{ image.image_thumbnail.url }}" /></td>
If there is any need for additional information please don't hesitate to ask.
Thank you in advance and I appreciate any help.
Edit: Today I tried another way and recognized that the error is only appearing to images that were uploaded with the django-admin-multiupload and not if only images are shown that were uploaded with the normal method. Maybe this could help to find a solution.

This error was mainly caused by a broken database that could be fixed by going back to an older version and reimplementing the new code. So there is no problem in django-admin-multiupload or django-imagekit.

Related

How can I make a page that will always display the latest post from my Django Model

Thank you to all of the people who looked at this in advance! I really appreciate it.
I have setup a very simple model that consists of two parameters (title, which is the date when this was published and the text, that's it):
models.py
class Post(models.Model):
title = models.DateField(blank=True, null=True)
body = models.TextField()
def __str__(self):
return str(self.title)
After following a standard "create a blog in Django tutorial" I have created two views that show the list of everything posted and a view that will show details of any selected post.
views.py
class NowListView(ListView):
model = Post
template_name = 'archive.html'
class NowDetailView(DetailView):
model = Post
template_name = 'then.html'
Finally, I have this urls.py that successfully shows all the posts at http://127.0.0.1:8000/now/archive and specific post at http://127.0.0.1:8000/now/archive/1 (or any other number, depending on the pk).
urls.py
urlpatterns = [
path('archive', NowListView.as_view(), name='archive'),
path('archive/<int:pk>', NowDetailView.as_view(), name='then'),
]
What I want to achieve is to display the latest post on http://127.0.0.1:8000/now.
I have tried a million ways to do it, and nothing worked, always something in the way (would take too long to write all of them). After all this tries it is obvious to me that I have to use a query to pull the latest post, but I have no working way of doing it.
I have tried using this Post.objects.earliest('title') and this Post.objects.order_by('title').first() in my urls as such:
urls.py
urlpatterns = [
path('archive', NowListView.as_view(), name='archive'),
path('archive/<int:pk>', NowDetailView.as_view(), name='then'),
path('>',NowDetailView.as_view(Post.objects.order_by('title').first()), name='then'),
]
This gives me an error:
TypeError: as_view() takes 1 positional argument but 2 were given
I have also tried creating a def function under my class in views.py, but the error then was that the urls couldn't import it for some reason.
In any case, I am probably over thinking it and just simply being stupid. If anyone could help me with this I would be very grateful! Thanks a ton in advance and sorry for the long question!
Best,
Rasul Kireev
This belongs in the view., not the URL.
You need to define get_object:
class NowLatestView(DetailView):
model = Post
template_name = 'then.html'
def get_object(self)
return Post.objects.order_by('title').first()

places maps with geojson in django error

i want to show some dynamic places in my web site and i follow this tutorial
geojson
models.py
class MushroomSpot(models.Model):
geom = PointField()
description = models.TextField()
picture = models.ImageField()
#property
def popupContent(self):
return '<img src="{}" /><p><{}</p>'.format(
self.picture.url,
self.description)
MushroomSpot is the ForeignKey to other models in my model
admin.py
from leaflet.admin import LeafletGeoAdmin
admin.site.register(MushroomSpot,LeafletGeoAdmin)
all work without error code.
but in my admin(administrator page) i cant to add points because dont show me the map.
administrator page
That is because you might need a widget in your form to show the map in the admin portal.
You can try django-leaflet library, they seem to support Leaflet maps form widgets.

400 error on django filefield model save

I'm using django 1.6.5 on python 2.7, and am trying to upload images with a form. My MEDIA_URL is '/uploads', MEDIA_ROOT='...../projectroot/uploads'.
My model:
class Picture(models.Model):
person = models.ForeignKey(User)
image = models.ImageField(upload_to='/images')
My Form field:
images = forms.ImageField(widget=forms.FileInput(), required=False)
My form saving:
image = self.cleaned_data['images']
picture = Picture(park=model, image=image)
picture.save()
I have tried setting the uploads folder permissions to 777 recursively, so django definitely has write access, but that didn't work. Somebody said the enctype on the form mattered, so I've set that to "multipart/form-data".
If it helps, only the actual saving creates the error (although that may have something to do with django just using lazy functions)

Uploading files in django admin, download through public site

I am running a Django website and I want to be able to upload a file through my admin panel and then have visitors to the main site be able to download it. I am running my site using Django-nonrel, Django FileTransfers and Google App Engine. I believe the upload functionality is working correctly as I am able to see the file in my App Engine Blob Storage. What I can't seem to figure out is how to present a download link to the specified file on the public website. I have pasted the relevant classes below:
I have an app called Calendar, that has the following model:
class CalendarEvent (models.Model):
start = models.DateTimeField(auto_now=False, auto_now_add=False)
end = models.DateTimeField(auto_now=False, auto_now_add=False)
title = models.CharField(max_length=500)
description = models.TextField()
file = models.FileField(upload_to='uploads/%Y/%m/%d/%H/%M/%S/')
Here is the view:
def calendar(request):
events = CalendarEvent.objects.exclude(start__lt=datetime.datetime.now()).order_by('start')
return render_to_response('home/calendar.html',{'events': events},context_instance=RequestContext(request))
def download_handler(request, pk):
upload = get_object_or_404(CalendarEvent, pk=pk)
return serve_file(request, upload.file, save_as=True)
Here is my admin:
class calendarAdmin(admin.ModelAdmin):
list_display = ('title','start','end')
admin.site.register(CalendarEvent, calendarAdmin)
Finally, here is the relevant part of my template:
{% for e in events %}
{% url Calendar.views.download_handler pk=e.pk as fallback_url %}
Download
{% endfor %}
{% firstof e.file|public_download_url fallback_url %} is just returning blank, i'm not sure where I am going wrong.
The GAE blob store does not support public download according to the documentation here, so if you use the default backend for public download urls, it returns None. So my guess is that e.file|public_download_url always return None. You could verify that.
Then I think your template is wrong. You're trying to access e.views.download_handler where it should be Calendar.views.download_handler if your app is named Calendar.
I think the sample on the django-filetransfers page is error prone because the variable used in the template loop has the same name as the sample app: "upload".
If this doesn't fix it, could you post your urls.py from Calendar app. It could be that the template's url method is not able to resolve the url for Calendar.views.download_handler if there is no mapping in urlpatterns.
You should have something like
urlpatterns = patterns('Calendar.views',
...
(r'^download/(?P<pk>.+)$', 'download_handler'),
...
)
in this file.
I don't see anything special, eg
Download File
should work, or just use e.file.url directly?
I haven't deployed on Google App Engine myself, but this appears to be what django-filetransfers was designed for:
http://www.allbuttonspressed.com/projects/django-filetransfers#handling-downloads
edit: I believe I've answered this in the other question you posted, then: Trouble downlaoding file using Django FileTransfers
I think easiest way is to write a view since this file blob cannot be retrieved directly to write a function which is such:
def file_transfer(req, calendar_event_id):
try:
ce = CalendarEvent.objects.get(calendar_event_id)
except CalendarEvent.DoesNotExist:
raise Http404()
file = ce.file (Write Google appengine specfic routine to pull file)
return HttpResponse(file, media_type='file content type')
Hook it up on urls.py

Attach an image into a Django Model

Making a basic Q&A site and want to associate each question with an image (admin uploaded) and if there is no respective image, puts it with a default "No Image" placeholder.
I have two models, Question and Answer (see below). Each question needs to have an image associated with it, so I thought the best way was to attach attribute ImageField with the Question model.
#models.py
class Question(models.Model):
title = models.CharField(max_length = 500)
picture = models.ImageField(height_field = '250',
width_field = '200',
upload_to = 'images')
def __unicode__(self):
return self.title
When I runserver though, tells me to download Python Imaging Library, and when I do get an error (different problem).
Taking a step back, what is the best way to add an image to a model in Django?
Forget PIL...
Use a location URL DB entry. Instead of having an ImageField(), use
picturepath = models.CharField(255)
that contains a URL to the static location of the image.
so if STATIC_URL = "http://127.0.0.1/static/"
and picturepath = "images/poots.png"
Then, pass that information along in the view, and use this in the template:
<img src="{{ STATIC_URL }}{{ question.picturepath }}">
will provide
<img src="http://127.0.0.1/static/images/poots.png">

Categories