Created
August 9, 2017 05:39
-
-
Save hjwp/ed03cf6ef1bd1431da8b71d4c7654985 to your computer and use it in GitHub Desktop.
a hideous hack to create a wagtail modeladmin view for a custom image class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.utils.translation import ugettext_lazy as _ | |
from django.utils.safestring import mark_safe | |
from django.forms.utils import flatatt | |
from django.shortcuts import redirect | |
from wagtail.wagtailimages.views.images import edit as image_edit_view | |
from wagtail.contrib.modeladmin import views | |
class StandardImageEditViewWrapper(views.EditView): | |
def get(self, request): | |
response = image_edit_view(request, self.instance_pk) | |
# hack the normal form post url so we can get redirected back to this view | |
standard_post_url = reverse('wagtailimages:edit', args=[self.instance_pk]) | |
response.content = response.content.decode('utf8').replace( | |
standard_post_url, self.edit_url | |
).encode('utf8') | |
return response | |
def post(self, request): | |
response = image_edit_view(request, self.instance_pk) | |
if response.status_code == 302: | |
# intercept redirects that would go back to normal image edit | |
# and bring them back here | |
return redirect(self.get_success_url()) | |
class ImageModelAdmin(ModelAdmin, ThumbnailMixin): | |
model = CustomImage | |
add_to_settings_menu = False | |
list_display = ('admin_thumb', 'title', 'production', 'castmember') | |
list_filter = ('production', 'castmember') | |
search_fields = ['title'] | |
menu_label = 'Categorised Images' | |
menu_icon = 'image' | |
menu_order = 106 | |
list_per_page = 20 | |
thumb_image_filter_spec = 'fill-100x100' | |
thumb_image_width = 100 | |
thumb_col_header_text = _('image') | |
def admin_thumb(self, obj): | |
# hacked version of ThumbnailMixin.admin_thumb but image=obj | |
img_attrs = { | |
'src': self.thumb_default, | |
'width': self.thumb_image_width, | |
'class': self.thumb_classname, | |
} | |
# try to get a rendition of the image to use | |
from wagtail.wagtailimages.shortcuts import get_rendition_or_not_found | |
spec = self.thumb_image_filter_spec | |
rendition = get_rendition_or_not_found(obj, spec) | |
img_attrs.update({'src': rendition.url}) | |
return mark_safe('<img{}>'.format(flatatt(img_attrs))) | |
admin_thumb.short_description = thumb_col_header_text | |
edit_view_class = StandardImageEditViewWrapper | |
modeladmin_register(ImageModelAdmin) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment