Set Default Page on Hue - django

I am new to Django. I'd like to make some edits to Hue (the Hadoop UI), and don't know what to change. I'd like to set the default page to the filebrowser, so that when a user logs in the first page they will go to is filebrowser. I know that Hue provides a redirect functionality with ?next=, but this does not work behind my VIP (when I point my VIP to the next URL, it redirects but then resolves to the true IP address rather than the virtual, which is not what I want). I'd like to hardwire changes so that the default URL is always the filebrowser, how can I do this?
My current strategy is to edit urls.py in /desktop/core/src/desktop and add the following line:
dynamic_patterns += patterns('filebrowser.views',
url(r'^$', 'index', name='index'),
)
However I keep getting the error:
Traceback:
File "/opt/mapr/hue/hue-3.6.0/build/env/lib/python2.6/site-packages/Django-1.4.5-py2.6.egg/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/opt/mapr/hue/hue-3.6.0/apps/filebrowser/src/filebrowser/views.py" in index
99. return view(request, path)
File "/opt/mapr/hue/hue-3.6.0/apps/filebrowser/src/filebrowser/views.py" in view
161. return listdir_paged(request, path)
File "/opt/mapr/hue/hue-3.6.0/apps/filebrowser/src/filebrowser/views.py" in listdir_paged
435. return render('listdir.mako', request, data)
File "/opt/mapr/hue/hue-3.6.0/desktop/core/src/desktop/lib/django_util.py" in render
222. **kwargs)
File "/opt/mapr/hue/hue-3.6.0/desktop/core/src/desktop/lib/django_util.py" in _render_to_response
144. return django_mako.render_to_response(template, *args, **kwargs)
File "/opt/mapr/hue/hue-3.6.0/desktop/core/src/desktop/lib/django_mako.py" in render_to_response
117. return HttpResponse(render_to_string(template_name, data_dictionary), **kwargs)
File "/opt/mapr/hue/hue-3.6.0/desktop/core/src/desktop/lib/django_mako.py" in render_to_string_normal
106. result = template.render(**data_dict)
File "/opt/mapr/hue/hue-3.6.0/build/env/lib/python2.6/site-packages/Mako-0.8.1-py2.6.egg/mako/template.py" in render
443. return runtime._render(self, self.callable_, args, data)
File "/opt/mapr/hue/hue-3.6.0/build/env/lib/python2.6/site-packages/Mako-0.8.1-py2.6.egg/mako/runtime.py" in _render
786. **_kwargs_for_callable(callable_, data))
File "/opt/mapr/hue/hue-3.6.0/build/env/lib/python2.6/site-packages/Mako-0.8.1-py2.6.egg/mako/runtime.py" in _render_context
818. _exec_template(inherit, lclcontext, args=args, kwargs=kwargs)
File "/opt/mapr/hue/hue-3.6.0/build/env/lib/python2.6/site-packages/Mako-0.8.1-py2.6.egg/mako/runtime.py" in _exec_template
844. callable_(context, *args, **kwargs)
File "/tmp/tmp13I5gT/filebrowser/listdir.mako.py" in render_body
73. __M_writer(escape(unicode( fb_components.menubar() )))
File "/tmp/tmp13I5gT/filebrowser/fb_components.mako.py" in render_menubar
260. __M_writer(escape(unicode(app_name)))
File "/opt/mapr/hue/hue-3.6.0/build/env/lib/python2.6/site-packages/Mako-0.8.1-py2.6.egg/mako/runtime.py" in __str__
205. raise NameError("Undefined")
Exception Type: NameError at /
Exception Value: Undefined

I have gained some more familiarity with Django now and was able to meet my requirement. To change the page that users are shown after logging in, edit the following file:
/desktop/core/src/desktop/views.py
In here we need to edit the index function - here is the before and after:
Old:
def index(request):
if request.user.is_superuser and request.COOKIES.get('hueLandingPage') != 'home':
return redirect(reverse('about:index'))
else:
return home(request)
New:
def index(request):
if request.user.is_superuser and request.COOKIES.get('hueLandingPage') != 'home':
return redirect('filebrowser.views.index')
#return redirect(reverse('about:index'))
else:
return redirect('filebrowser.views.index')
#return home(request)
You can write it how you like (clearly the if condition isn't important here) but the important point is to have this function return redirect('filebrowser.views.index')
Note: I have used this workaround with Hue 3.6 and Hue 3.7

Related

How to choose a Wagtail image across a ParentalManyToManyField?

Environment:
Wagtail 1.13
Django Version: 1.11.11
Python Version: 2.7.12
I'm following the Wagtail documentation to try to add an image showcase (not a category) to a page using ParentalManyToManyField:
class HomePage(Page):
showcase_title = models.CharField(max_length=100, blank="true", default="SHOWCASE")
showcase_images = ParentalManyToManyField('wagtailimages.Image')
content_panels = Page.content_panels + [
FieldPanel('showcase_title'),
InlinePanel('showcase_images', label="Showcase images", panels=[
ImageChooserPanel('showcase_images')
]),
]
Everything is fine if I comment out the showcase_images editing panel, but I get a KeyError as soon as uncomment the panel showcase_images. In addition to the above variation of editing showcase_images, I've also tried simply InlinePanel('showcase_images'), FieldPanel('showcase_images'), InlinePanel('showcase_images', label="Showcase images", panels=[ImageChooserPanel('image')]), and probably another variation or two. Can someone propose a solution?
Environment:
Request Method: GET
Request URL: http://dev.somedomain.com:8181/admin/pages/3/edit/
Django Version: 1.11.11
Python Version: 2.7.12
Installed Applications:
[u'my_app',
u'search',
u'wagtail.wagtailforms',
u'wagtail.wagtailredirects',
u'wagtail.wagtailembeds',
u'wagtail.wagtailsites',
u'wagtail.wagtailusers',
u'wagtail.wagtailsnippets',
u'wagtail.wagtaildocs',
u'wagtail.wagtailimages',
u'wagtail.wagtailsearch',
u'wagtail.wagtailadmin',
u'wagtail.wagtailcore',
u'wagtail.contrib.wagtailstyleguide',
u'modelcluster',
u'taggit',
u'wagtailfontawesome',
u'django.contrib.admin',
u'django.contrib.auth',
u'django.contrib.contenttypes',
u'django.contrib.sessions',
u'django.contrib.messages',
u'django.contrib.staticfiles']
Installed Middleware:
[u'django.contrib.sessions.middleware.SessionMiddleware',
u'django.middleware.common.CommonMiddleware',
u'django.middleware.csrf.CsrfViewMiddleware',
u'django.contrib.auth.middleware.AuthenticationMiddleware',
u'django.contrib.messages.middleware.MessageMiddleware',
u'django.middleware.clickjacking.XFrameOptionsMiddleware',
u'django.middleware.security.SecurityMiddleware',
u'wagtail.wagtailcore.middleware.SiteMiddleware',
u'wagtail.wagtailredirects.middleware.RedirectMiddleware']
Traceback:
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/django/views/decorators/cache.py" in _cache_controlled
43. response = viewfunc(request, *args, **kw)
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/wagtail/wagtailadmin/urls/__init__.py" in wrapper
96. return view_func(request, *args, **kwargs)
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/wagtail/wagtailadmin/decorators.py" in decorated_view
31. return view_func(request, *args, **kwargs)
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/wagtail/wagtailadmin/views/pages.py" in edit
481. edit_handler = edit_handler_class(instance=page, form=form)
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/wagtail/wagtailadmin/edit_handlers.py" in __init__
269. self.children.append(child(instance=self.instance, form=self.form))
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/wagtail/wagtailadmin/edit_handlers.py" in __init__
269. self.children.append(child(instance=self.instance, form=self.form))
File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/wagtail/wagtailadmin/edit_handlers.py" in __init__
693. self.formset = form.formsets[self.__class__.relation_name]
Exception Type: KeyError at /admin/pages/3/edit/
Exception Value: u'showcase_images'
InlinePanel doesn't work with ParentalManyToManyField relations, only ParentalKey relations. You'll need to set up an intermediate model to define the relation between pages and images, like BlogPageGalleryImage in the tutorial's 'images' section (but with the caption field omitted in this case, so it's just a direct association between pages and images).
(Alternatively, you can use a plain FieldPanel with ParentalManyToManyField, but this will just give you a set of checkboxes for all images in the system, rather than the the image chooser interface.)

Error with prewarming VersatileImageField

I've implemented django-versatileimagefield and have gotten it to a state where I can successfully resize images in templates with the use of the following tag, for example:
As a result, I'm confident that my form.py, view.py, and template works. I have, however, recently tried to 'prewarm' the images so that when a user saves an image, a set of resized images are saved to my 'media' folder. This prevents the server from having to resize dynamically on every page load and can just grab the correctly sized image.
My problem is that when the user goes to save an image within the image upload form, they get an error.
Settings.py
VERSATILEIMAGEFIELD_SETTINGS = {
'cache_length': 2592000,
'cache_name': 'versatileimagefield_cache',
'jpeg_resize_quality': 70,
'sized_directory_name': '__sized__',
'filtered_directory_name': '__filtered__',
'placeholder_directory_name': '__placeholder__',
'create_images_on_demand': False,
'image_key_post_processor': None,
'progressive_jpeg': False
}
VERSATILEIMAGEFIELD_RENDITION_KEY_SETS = {
'image_gallery': [
('image_large', 'thumbnail__400x400'),
('image_small', 'thumbnail__900x900')
]
}
models.py
from django.db import models
from django.db.models.signals import post_save
from versatileimagefield.fields import VersatileImageField
from django.dispatch import receiver
from versatileimagefield.image_warmer import VersatileImageFieldWarmer
class ImageGallery(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
image = VersatileImageField('image_gallery', upload_to=upload_location)
def __str__(self):
return self.author.username
#receiver(models.signals.post_save, sender=ImageGallery)
def warm_gallery_images(sender, instance, **kwargs):
gallery_img_warmer = VersatileImageFieldWarmer(
instance_or_queryset=instance,
rendition_key_set='image_gallery',
image_attr='image_small'
)
num_created, failed_to_create = gallery_img_warmer.warm()
Traceback
Environment:
Traceback:
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "C:\Users\jason\Desktop\jason\accounts\views.py" in imagegallery
513. instance.save()
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py" in save
729. force_update=force_update, update_fields=update_fields)
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py" in save_base
769. update_fields=update_fields, raw=raw, using=using,
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\dispatch\dispatcher.py" in send
178. for receiver in self._live_receivers(sender)
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\dispatch\dispatcher.py" in <listcomp>
178. for receiver in self._live_receivers(sender)
File "C:\Users\jason\Desktop\jason\accounts\models.py" in warm_gallery_images
177. num_created, failed_to_create = gallery_img_warmer.warm()
File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\versatileimagefield\image_warmer.py" in warm
143. reduce(getattr, self.image_attr.split("."), instance)
Exception Type: AttributeError at /accounts/profile/websitesetup5/upload/
Exception Value: 'ImageGallery' object has no attribute 'image_small'
I feel like I've followed the instructions on this page, but I'm still getting this error.
http://django-versatileimagefield.readthedocs.io/en/latest/improving_performance.html#turning-off-on-demand-image-creation
I should note that I do NOT have django REST framework installed. My understanding is that it's not required for this post-save method of prewarming images.
Thanks so much!
It looks like the image_attr field should point to the model field image:
#receiver(models.signals.post_save, sender=ImageGallery)
def warm_gallery_images(sender, instance, **kwargs):
gallery_img_warmer = VersatileImageFieldWarmer(
instance_or_queryset=instance,
rendition_key_set='image_gallery',
image_attr='image'
)
num_created, failed_to_create = gallery_img_warmer.warm()

Error using ModelResource: can't set attribute

I can't get my head around this error... I'm using the restframework2 branch.
Am I doing something wrong, or is this a bug in the restframework2 code?
Here's my code:
resources.py
class TemplateHoursSerializer(serializers.ModelSerializer):
class Meta:
model = TemplateHours
nested = True
start = HourField()
end = HourField()
employee = EmployeeSerializer()
class TemplateHoursResource(ModelResource):
model = TemplateHours
serializer_class = TemplateHoursSerializer
urls.py
url(r'^api/template-hours/$', TemplateHoursResource.as_view(actions={
'get': 'list',
'post': 'create'
})),
url(r'^api/template-hours/(?P<pk>[0-9]+)/$', TemplateHoursResource.as_view(actions={
'get': 'retrieve',
'put': 'update',
'delete': 'destroy'
})),
...
When I visit (or POST to) http://127.0.0.1:8000/api/template-hours/, I get this error and traceback:
AttributeError at /api/template-hours/
can't set attribute
Request Method: GET
Request URL: http://127.0.0.1:8000/api/template-hours/
Django Version: 1.4.1
Exception Type: AttributeError
Exception Value:
can't set attribute
Exception Location: C:\Users\Mathieu\Development\django_projects\hedron\Lib\site- packages\rest_framework\resources.py in wrapped, line 13
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
Python Path:
['C:\\Users\\Mathieu\\Development\\django_projects\\hedron\\Scripts',
'C:\\Python27\\lib\\site-packages\\setuptools-0.6c12dev_r88846-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\virtualenv-1.7.1.2-py2.7.egg',
'C:\\Users\\Mathieu\\Development\\django_projects\\hedron\\Lib\\site-packages',
'C:\\Users\\Mathieu\\Development\\django_projects\\hedron\\hedron',
'C:\\Python27\\python27.zip',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
path(u'C:\\Users\\Mathieu\\Development\\django_projects\\hedron'),
path(u'C:\\Users\\Mathieu\\Development\\django_projects\\hedron\\hedron\\apps'),
path(u'C:\\Users\\Mathieu\\Development\\django_projects\\hedron\\hedron\\libs')]
Server time: di, 9 Okt 2012 22:46:50 +0200
Traceback:
File "C:\Users\Mathieu\Development\django_projects\hedron\Lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Mathieu\Development\django_projects\hedron\Lib\site-packages\rest_framework\resources.py" in view
48. return self.dispatch(request, *args, **kwargs)
File "C:\Users\Mathieu\Development\django_projects\hedron\Lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
77. return view_func(*args, **kwargs)
File "C:\Users\Mathieu\Development\django_projects\hedron\Lib\site-packages\rest_framework\views.py" in dispatch
324. response = self.handle_exception(exc)
File "C:\Users\Mathieu\Development\django_projects\hedron\Lib\site-packages\rest_framework\views.py" in dispatch
321. response = handler(request, *args, **kwargs)
File "C:\Users\Mathieu\Development\django_projects\hedron\Lib\site-packages\rest_framework\resources.py" in list
74. return self.root_view().list(request, args, kwargs)
File "C:\Users\Mathieu\Development\django_projects\hedron\Lib\site-packages\rest_framework\resources.py" in root_view
68. return wrapped(self, self.root_class())
File "C:\Users\Mathieu\Development\django_projects\hedron\Lib\site-packages\rest_framework\resources.py" in wrapped
13. setattr(dest, attr, getattr(source, attr))
Exception Type: AttributeError at /api/template-hours/
Exception Value: can't set attribute
Resources and routers are not finished/supported in [the beta of] REST framework 2 yet. The docs on them are a placeholder for what I want the design to look like, but I'll be removing them from the index today. Hopefully they'll make it in for 2.0, but I don't see it as at all essential, since you can do everything you need with Views and explicit URLconfs. Resources & routers just give you a useful shortcut.

django custom templatetag not getting request in context

I am using django 1.4 and trying to convert the code described at the end of this article into a customtag. This means I need access to the is_secure and site_name values from the request. Here is my CONTEXT_PROCESSORS in settings.py:
CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.contrib.auth.context_processors.auth',
)
Here is my template tag code:
from django import template
register = template.Library()
#register.simple_tag(takes_context=True)
def full_static_url(context, url):
request = context['request']
scheme = 'http'
if request.is_secure:
scheme += 's'
return scheme + '://' + request.site_name + context['STATIC_URL'] + url
In my view code I am using the new render shortcut like so:
return render(request, 'myapp/mytemplate.html', {'foo':bar})
And I am calling it like this in the template:
{% full_static_url "images/logo.gif" %}
The problem is, when it gets to the line request = context['request'] it throws a KeyError because 'request' is not in context.
What am I doing wrong here?
Full traceback is:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Projects\blah\blah\myapp\views\myview.py" in manifestcosts
44. return render(request, 'myapp/mytemplate.html', {'foo':bar})
File "C:\Python27\lib\site-packages\django\shortcuts\__init__.py" in render
44. return HttpResponse(loader.render_to_string(*args, **kwargs),
File "C:\Python27\lib\site-packages\django\template\loader.py" in render_to_string
176. return t.render(context_instance)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
140. return self._render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in _render
134. return self.nodelist.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
823. bit = self.render_node(node, context)
File "C:\Python27\lib\site-packages\django\template\debug.py" in render_node
74. return node.render(context)
File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in render
185. nodelist.append(node.render(context))
File "C:\Python27\lib\site-packages\django\template\base.py" in render
1107. return func(*resolved_args, **resolved_kwargs)
File "C:\Projects\blah\blah\myapp\templatetags\mytags.py" in full_static_url
25. request = context['request'] #TODO this fails with an KeyError, don't know why
File "C:\Python27\lib\site-packages\django\template\context.py" in __getitem__
54. raise KeyError(key)
Exception Type: KeyError at /myapp/myurl/110505081136179000/
Exception Value: 'request'
The right way to fix this issue is to add TEMPLATE_CONTEXT_PROCESSORS += ("django.core.context_processors.request",) on your settings.py file.
Ensure to import TEMPLATE_CONTEXT_PROCESSORS first with from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS or it will not work.
Most likely the problem is you are rendering your template using regular context, that is something like this:
return render_to_response("myapp/template.html", {"some_var": a_value})
Remember that context processors are only applied to RequestContext instances. That means you have to either explicitly create a RequestContext in your render_to_response call:
return render_to_response("myapp/template.html", {"some_var": a_value},
context_instance=RequestContext(request))
or even better, use the new render shortcut:
return render(request, "myapp/template.html", {"some_var": a_value})
I solved it by changing
return render(request, 'myapp/mytemplate.html', {'foo':bar})
to
return render( RequestContext(request), 'myapp/mytemplate.html', {'foo':bar})
I hope this helps someone else, I wasted about 8 hours :p
I had this happen in a template.Node object in the render(). It turned out that sometimes the context had 'request' in it, other times it didn't.
Like someone else suggested, RequestContext(request) is the key. My guess is that sometimes the context is called without the request being initialized like that.
I changed my function from
def render(self, context):
request = context['request'] # Failing here
to
def render(self, context):
request = RequestContext(context)['request']['request']
and it all came right.
This will force a request object in case the context object wasn't initialized properly. For some reason I had to add ['request'] twice, but it seems to work fine
EDIT: I spoke too soon, seems a blank context can't be fixed. Instead you could try a workaround:
request = context.get('request')
if request is None:
return ''
My page still seems to work fine, so I'm not exactly sure where these bad contexts are coming from.

Displaying PDFs in django; decoding error

I'm trying to pass a PDF into a Django app and am running into an issue with unicode/decoding the PDF. The PDFs are being stored in a mysql database, in a mediumblob field. I'd appreciate any help on this, as it seems the encoding is running into a problem with the metadata of the PDF, and I'm not sure where to go with this - I've checked out several questions that seem similar but can't find what I'm looking for. Do I need to decode/recode the PDFs somehow? Thanks!
Here is the error:
Request Method: POST
Request URL: http://0.0.0.0:8000/admin/pdf/abc/
Exception Type: DjangoUnicodeDecodeError
Exception Value: 'utf8' codec can't decode byte 0x89 in position 614: unexpected code byte
Exception Location: /usr/lib/python2.5/site-packages/django/utils/encoding.py in force_unicode, line 92
Python Executable: /usr/bin/python
My code is below:
class ABCAdmin(admin.ModelAdmin):
actions = ['print_selected_pdf']
def get_user(self):
return '%s'%(self.user.username)
def create_pdf(self, queryset):
response = HttpResponse(mimetype="applicaton/pdf")
response['Content-Disposition'] = 'attachment; filename=form.pdf'
p=canvas.Canvas(response)
# loop through the objects
for obj in queryset:
string1 = (obj.form)
# update the label_printed to true
obj.pdf_printed=True
obj.save()
p.save()
return response
def print_selected_pdf(self, request, queryset):
# prints the pdfs for those that are selected,
# regardless if the pdf_printed field is true or false
return self.create_pdf(queryset.order_by('user'))
print_selected_pdf.short_description = "Print selected PDF"
get_user.short_description='Printed By'
list_display=('form_no',get_user,'request_date','pdf_printed')
def queryset(self,request):
# get the user id
user = User.objects.get(username=request.user)
if request.user.is_superuser:
qs = self.model._default_manager.all()
else:
qs = self.model._default_manager.filter(user=user.id)
return qs
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "user" and not request.user.is_superuser:
# get the user id
user = User.objects.get(username=request.user)
kwargs["queryset"]=User.objects.filter(id=user.id)
return db_field.formfield(**kwargs)
return super(ABCAdmin,self).formfield_for_foreignkey(
db_field, request, **kwargs)
admin.site.register(ABC, ABCAdmin)
Edit: Full trackback:
Environment:
Request Method: POST
Request URL: http://0.0.0.0:8000/admin/pdf/abc/
Django Version: 1.1
Python Version: 2.5.2
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'app.pdf']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
Traceback:
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.5/site-packages/django/contrib/admin/options.py" in wrapper
226. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/lib/python2.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "/usr/lib/python2.5/site-packages/django/contrib/admin/sites.py" in inner
186. return view(request, *args, **kwargs)
File "/usr/lib/python2.5/site-packages/django/contrib/admin/options.py" in changelist_view
912. response = self.response_action(request,queryset=cl.get_query_set())
File "/usr/lib/python2.5/site-packages/django/contrib/admin/options.py" in response_action
694. response = func(self, request, queryset.filter(pk__in=selected))
File ".../pdf/admin.py" in print_selected_pdf
56. return self.create_pdf(queryset.order_by('user'))
File ".../pdf/admin.py" in create_pdf
48. obj.save()
File "/usr/lib/python2.5/site-packages/django/db/models/base.py" in save
410. self.save_base(force_insert=force_insert, force_update=force_update)
File "/usr/lib/python2.5/site-packages/django/db/models/base.py" in save_base
474. rows = manager.filter(pk=pk_val)._update(values)
File "/usr/lib/python2.5/site-packages/django/db/models/query.py" in _update
444. return query.execute_sql(None)
File "/usr/lib/python2.5/site-packages/django/db/models/sql/subqueries.py" in execute_sql
120. cursor = super(UpdateQuery, self).execute_sql(result_type)
File "/usr/lib/python2.5/site-packages/django/db/models/sql/query.py" in execute_sql
2369. cursor.execute(sql, params)
File "/usr/lib/python2.5/site-packages/django/db/backends/util.py" in execute
22. sql = self.db.ops.last_executed_query(self.cursor, sql, params)
File "/usr/lib/python2.5/site-packages/django/db/backends/__init__.py" in last_executed_query
213. u_params = tuple([to_unicode(val) for val in params])
File "/usr/lib/python2.5/site-packages/django/db/backends/__init__.py" in <lambda>
211. to_unicode = lambda s: force_unicode(s, strings_only=True)
File "/usr/lib/python2.5/site-packages/django/utils/encoding.py" in force_unicode
92. raise DjangoUnicodeDecodeError(s, *e.args)
Exception Type: DjangoUnicodeDecodeError at /admin/pdf/abc/
Exception Value: 'utf8' codec can't decode byte 0x89 in position 614: unexpected code byte. You passed in [redacted for length - here it displayed all of the metadata in the PDF]
The PDFs are being stored in a mysql database, in a mediumblob field.
You just lost the game. Use a FileField instead.
I had to use a queryset to avoid the decoding error. Filefield is not practical in my situation.