Error using ModelResource: can't set attribute - django

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.

Related

Unable to perform conditional redirect from a class based view Django

I am trying to redirect a user who has already registered to a different view. here is the code for the views.py
However when qs.exists() = true I get an error
'The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.'
I am a beginner have read the documentation but unable to find where i am going worng.
Thanks
from django.shortcuts import render, redirect
from django.views import View
from Lpage.forms import SubscriberEntryForm
from Lpage.models import Subscriber
class homeview(View):
def get(self,request):
msg = request.session.get('msg', False)
if(msg):
del(request.session['msg'])
return render(request,'Lpage/index.html')
def post(self, request):
form = SubscriberEntryForm(request.POST or None)
if form.is_valid():
obj = form.save(commit=False)
qs = Subscriber.objects.filter(email__iexact=obj.email)
if qs.exists():
return redirect('messageview')
else:
obj.save()
request.session['msg'] = "msg"
return redirect(request.path)
def messageview(request):
return render(request,'Lpage/messages.html',{})
Here is the error message
ValueError at /
The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.
Request Method: POST
Request URL: http://localhost:8000/
Django Version: 3.2.7
Exception Type: ValueError
Exception Value:
The view Lpage.views.homeview didn't return an HttpResponse object. It returned None instead.
Exception Location: C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 309, in check_response
Python Executable: C:\Users\Ganesamurthi\anaconda3\python.exe
Python Version: 3.8.5
Python Path:
['D:\dreamdoors\dd',
'C:\Users\Ganesamurthi\anaconda3\python38.zip',
'C:\Users\Ganesamurthi\anaconda3\DLLs',
'C:\Users\Ganesamurthi\anaconda3\lib',
'C:\Users\Ganesamurthi\anaconda3',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\win32',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\win32\lib',
'C:\Users\Ganesamurthi\anaconda3\lib\site-packages\Pythonwin']
Server time: Wed, 29 Sep 2021 05:23:43 +0000
Traceback Switch to copy-and-paste view
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\exception.py, line 47, in inner
response = get_response(request) …
▶ Local vars
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 188, in _get_response
self.check_response(response, callback) …
▶ Local vars
C:\Users\Ganesamurthi\anaconda3\lib\site-packages\django\core\handlers\base.py, line 309, in check_response
raise ValueError( …
▶ Local vars
redirect expects you to pass a URL but you gave it messageview, which is a view class in fact.
So you need to give redirect to the URL of messageview.

MultiValueDictKeyError when deleting related inline records in another tab

I'll try to be as concise as possible.
Background
I have a model Person which has a ForeignKey to model Document. Each Person can only have one Document but, as you may already know, each Document can be linked to many Persons.
In the Document's Admin form I have the Persons associated to the Document displayed inline. I can edit, add or delete the Persons right there.
Problem
Following these steps I get the error:
I open the Admin edit form for a Document. Let's call it Document
A. This Document has two Persons associated, let's call them John
Doe and Jane Doe. You can see them there (inline) in the form and
the fields are editable, but I don't touch them.
I open another tab and go straight to the Persons list and delete
Jane Doe.
I get back to the first tab (the Document's edit form) and click on
"Save and continue editing".
The form is sent and I get a generic error at the top (something
like) "Please, fix the following errors". But the form shows no
errors (next to the fields) to correct and, obviously, the record
for Jane Doe isn't displayed.
I click again on "Save and continue editing" and when the form is
sent I get the error "MultiValueDictKeyError: "u'person_set-1-id'"".
Ideal solution
I'd like to be able to display a custom error in the middle stage (when the first error appears, after the first save), saying something like "A person associated with this Document was deleted while you were editing it". Also, preventing the final error is highly desirable.
Error dump
MultiValueDictKeyError at /admin/persons/document/1145/
"u'person_set-1-id'"
Request Method: POST
Request URL: http://localhost:8000/admin/persons/document/1145/
Django Version: 1.7.7
Exception Type: MultiValueDictKeyError
Exception Value:
"u'person_set-1-id'"
Exception Location: /__PATH__/local/lib/python2.7/site-packages/django/utils/datastructures.py in __getitem__, line 319
Python Executable: /__PATH__/bin/python
Python Version: 2.7.15
Python Path:
['/__PATH__/test/test/apps',
'/__PATH__/test',
'/__PATH__/lib/python2.7',
'/__PATH__/lib/python2.7/plat-x86_64-linux-gnu',
'/__PATH__/lib/python2.7/lib-tk',
'/__PATH__/lib/python2.7/lib-old',
'/__PATH__/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/__PATH__/local/lib/python2.7/site-packages',
'/__PATH__/src/django-smart-selects',
'/__PATH__/lib/python2.7/site-packages',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/test']
Server time: Mar, 29 Ene 2019 11:52:18 -0300
Environment:
Request Method: POST
Request URL: http://localhost:8000/admin/persons/document/1145/
Django Version: 1.7.7
Python Version: 2.7.15
Installed Applications:
('salmonella',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'crispy_forms',
'test.apps.persons',
'captcha',
'django_countries',
'django_extensions',
'import_export',
'django_object_actions',
'widget_tweaks',
'smart_selects',
'daterange_filter',
'compressor',
'auditlog')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'auditlog.middleware.AuditlogMiddleware')
Traceback:
File "/__PATH__/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
583. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
206. return view(request, *args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in change_view
1456. return self.changeform_view(request, object_id, form_url, extra_context)
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
25. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/__PATH__/local/lib/python2.7/site-packages/django/db/transaction.py" in inner
394. return func(*args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in changeform_view
1403. if all_valid(formsets) and form_validated:
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in all_valid
438. if not formset.is_valid():
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in is_valid
303. self.errors
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in errors
277. self.full_clean()
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in full_clean
325. form = self.forms[i]
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/functional.py" in __get__
55. res = instance.__dict__[self.func.__name__] = self.func(instance)
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in forms
141. forms = [self._construct_form(i) for i in xrange(self.total_form_count())]
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/models.py" in _construct_form
868. form = super(BaseInlineFormSet, self)._construct_form(i, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/models.py" in _construct_form
581. pk = self.data[pk_key]
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/datastructures.py" in __getitem__
319. raise MultiValueDictKeyError(repr(key))
Exception Type: MultiValueDictKeyError at /admin/persons/document/1145/
Exception Value: "u'person_set-1-id'"
UPDATE
I'm adding the definitions for models Person and Document.
class Document(models.Model):
creation_date = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=300, null=True, blank=True)
class Person(models.Model):
first_name = models.CharField(max_length=300)
last_name = models.CharField(max_length=300)
email = models.EmailField(max_length=300)
document = models.ForeignKey(Document)
UPDATE 2
One important thing I noticed is that, in the first error page (after the first submission of Document A form) the hidden inputs like person_set-TOTAL_FORMS and person_set-INITIAL_FORMS are set to 2 while they should be set to 1 (the actual number of persons). Obviously this happens because the submitted data doesn't reflect the actual database state.

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.)

Set Default Page on Hue

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

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.