Displaying PDFs in django; decoding error - django

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.

Related

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.

Django RestFramework _'NoneType' object has no attribute 'token'

I have this Serializer class for my User model:
serializers.py
class UserCreateSerializer(serializers.ModelSerializer):
"""User django serilization"""
key = serializers.StringRelatedField(source='key.token', read_only=True)
class Meta:
model = User
fields = ['phonenumber','id','email', 'username', 'key' ]
def create(self, validate_data):
user = User(**validate_data)
user.save()
return user
and this views.py
class UserListView(ListAPIView):
'''listing all users'''
permission_classes = (AllowAny,)
pagination_class = SmallPagination
throttle_classes = (UserRateThrottle, AnonRateThrottle,)
serializer_class = UserCreateSerializer
queryset = User.objects.all()
filter_backends = (filters.SearchFilter,)
search_fields = ('username', 'phonenumber', 'email')
I include 'rest_framework.authtoken', in my settings.py
and made a signal for Tokens from django Restframe work documentation.
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
urls.py
urlpatterns = [
re_path(r'^users/$', views.UserListView.as_view(), name='user-list'),]
so when I try to load my users List this error occurs :
'NoneType' object has no attribute 'token'
for attr in attrs:
try:
if isinstance(instance, collections.Mapping):
instance = instance[attr]
else:
instance = getattr(instance, attr) ...
except ObjectDoesNotExist:
return None
if is_simple_callable(instance):
try:
instance = instance()
except (AttributeError, KeyError) as exc:
....
the error location is from :
/backend/env/lib/python3.6/site-packages/rest_framework/fields.py in
get_attribute
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/api/users/create/
Django Version: 2.0
Python Version: 3.6.3
Installed Applications:
['django.contrib.admin',
'main.apps.MainConfig',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'stdimage',
'rest_framework.authtoken',
'blog',
'taggit',
'taggit_serializer',
'django.contrib.sites',
'corsheaders',
'webpack_loader']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
494. response = self.handle_exception(exc)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
454. self.raise_uncaught_exception(exc)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
491. response = handler(request, *args, **kwargs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/generics.py" in post
192. return self.create(request, *args, **kwargs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/mixins.py" in create
22. headers = self.get_success_headers(serializer.data)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/serializers.py" in data
537. ret = super(Serializer, self).data
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/serializers.py" in data
262. self._data = self.to_representation(self.instance)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/serializers.py" in to_representation
491. attribute = field.get_attribute(instance)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/relations.py" in get_attribute
177. return get_attribute(instance, self.source_attrs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/fields.py" in get_attribute
100. instance = getattr(instance, attr)
Exception Type: AttributeError at /api/users/create/
Exception Value: 'NoneType' object has no attribute 'token'
authtoken model has related_name=auth_token to user models. So if you need to get token from user you should use auth_token.key:
key = serializers.StringRelatedField(source='auth_token.token', read_only=True)
I also got stuck in this error. But luckily i found the mistake i was doing.
I know its already been some time now. Still answering this question for newbies stuck in such silly error.
If we have to use Token model we have to mention the same in Installed Apps in settings.py file
'rest_framework.authtoken'
After that do migrate and you will see creation of new tables in the db.
Afterwards you can query the database like this...
Token.objects.all()
and you are good to go now.
Happy coding.

KeyError 'id' when trying to access request.data in ViewSet create definition

I recently upgraded from drf 2.4 to v3 and have been trying to override the def Create in one of my ViewSets. However when trying to access the request.data that i've saved to a serializer variable i'll receive an error: KeyError at /api/appointments/
'id'
I'm including my ViewSet code, serializer, and the traceback from the error below:
class AppointmentViewSet(viewsets.ModelViewSet):
queryset = Appointment.objects.all()
serializer_class = AppointmentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
def create(self, request):
serializer = AppointmentSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
#get the datetime object from the request data and filter availability objects, datetime stored in attribute .when
avQueryset = Availability.objects.filter(date__range=(serializer.data.when, serializer.data.when))
def pre_save(self, obj):
obj.service_recipient = self.request.user
Serializer
class AppointmentSerializer(serializers.ModelSerializer):
class Meta:
model = Appointment
fields = ('id','availability' , 'business_location', 'services', 'when', 'service_recipient', 'completed')
repr(serializer)
AppointmentSerializer():
id = IntegerField(label='ID', read_only=True)
availability = PrimaryKeyRelatedField(queryset=Availability.objects.all())
business_location = PrimaryKeyRelatedField(queryset=BusinessLocation.objects.all())
services = PrimaryKeyRelatedField(many=True, queryset=Service.objects.all())
when = DateTimeField(allow_null=True, required=False)
service_recipient = PrimaryKeyRelatedField(queryset=User.objects.all())
completed = BooleanField(help_text='Set to true when appointment has been completed.', required=False)
Traceback
Environment:
Request Method: POST
Request URL: http://104.131.110.138/api/appointments/
Django Version: 1.7.1
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'webapp',
'rest_framework')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view
57. return view_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/viewsets.py" in view
85. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py" in dispatch
407. response = self.handle_exception(exc)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py" in dispatch
404. response = handler(request, *args, **kwargs)
File "/home/appointments/appointments/webapp/views.py" in create
57. avQueryset = Availability.objects.filter(date__range=(serializer.data.when, serializer.data.when))
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in data
422. ret = super(Serializer, self).data
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in data
179. self._data = self.to_representation(self.validated_data)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in to_representation
387. attribute = field.get_attribute(instance)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/fields.py" in get_attribute
277. return get_attribute(instance, self.source_attrs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/fields.py" in get_attribute
65. instance = instance[attr]
Exception Type: KeyError at /api/appointments/
Exception Value: 'id'
You are using serializer.data when you appear to mean to be using serializer.validated_data. You should really only use serializer.data when you are looking to serialize an existing object, which would require passing an instance into the serialier when you are initializing it.
The issue is that you are not passing an instance into the serializer, so it is expecting that the initial data passed into it can be serialized. This would require the data to have all of the fields on the serializer, including id which doesn't appear to exist.
You can get the validated data, not the serialized data, using serializer.validated_data["when"]. This is specifically mentioned in the documentation for Django REST Framework under deserializing objects.

Integrity Error May not be null

I am building a website similar to a bartering website, but we are bartering Time,
I have a class Transaction, where it takes the "offer" value, deductions that value from the balance of the requesting user, and credits the value to the Offer'r.
Right now when I click on "Accept Offer" from my template I get this error
ofertoj_transaction.accepted_by may not be NULL
Stacktrace:
IntegrityError at /oferto/accept/
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/oferto/accept/?offer_id=1&creator=2
Django Version: 1.5.4
Python Version: 2.7.4
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.comments',
'django.contrib.sitemaps',
'zinnia',
'tagging',
'mptt',
'south',
'registration',
'blogs',
'turtle',
'ofertoj',
'petoj',
'x',
'profiles')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/views/generic/base.py" in dispatch
86. return handler(request, *args, **kwargs)
File "/home/talisman/projects/tempilo/ofertoj/views.py" in get
74. accepted_by=self.request.user.id
File "/home/talisman/projects/tempilo/ofertoj/models.py" in create
59. new_transaction.save()
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/base.py" in save
546. force_update=force_update, update_fields=update_fields)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/base.py" in save_base
650. result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/manager.py" in _insert
215. return insert_query(self.model, objs, fields, **kwargs)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/query.py" in insert_query
1675. return query.get_compiler(using=using).execute_sql(return_id)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/sql/compiler.py" in execute_sql
937. cursor.execute(sql, params)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/backends/util.py" in execute
41. return self.cursor.execute(sql, params)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/backends/sqlite3/base.py" in execute
364. six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/backends/sqlite3/base.py" in execute
362. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /oferto/accept/
Exception Value: ofertoj_transaction.accepted_by may not be NULL
part of ofertoj.views.py
class TransactionView(TemplateView, LoginRequiredMixin):
template_name = "ofertoj/offer_accepted.html"
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
if self.request.GET.get("offer_id"):
oferto = Oferto.objects.get(id=self.request.GET.get("offer_id"))
if oferto.valid:
transaction = Transaction()
transaction.create(
creator=self.request.GET.get("creator"),
amount=oferto.time,
accepted_by=self.request.user.id
)
acceptor = Profile.objects.get(user=self.request.user)
acceptor.balance = acceptor.balance - oferto.time
acceptor.save()
# credit the coins to the creator
creator = Profile.objects.get(user=oferto.user)
creator.balance = creator.balance + oferto.time
creator.save()
else:
return HttpResponse("This offer is already accepted")
else:
raise Http404
return self.render_to_response(context)
Part of Ofertoj.models
class Transaction(models.Model):
creator = models.IntegerField()
amount = models.IntegerField()
accepted_by = models.IntegerField()
def __unicode__(self):
return self.id
def create(self, **kwargs):
new_transaction = Transaction(
creator = kwargs['creator'],
amount = kwargs['amount'],
accepted_by = kwargs['accepted_by']
)
new_transaction.save()
return
this line is highlited in the stacktrace
acceptor = Profile.objects.get(user=self.request.user)
ofertoj.urls
url(
regex=r"^accept/$",
view = TransactionView.as_view(),
name = "accept_offer"
),
part of my template
{% if oferto.valid and not oferto.user == request.user %}
Accept this Offer
{% endif %}
<br /><br />
Your ofertoj application is trying to store a Transaction object which has an accepted_by field which is NULL but your database schema does not allow this field to be NULL.
Check this code:
transaction.create(
creator=self.request.GET.get("creator"),
amount=oferto.time,
accepted_by=self.request.user.id
)
and the code of transaction.create.
One possibility: if your user is not logged in then self.request.user.id will be None, and this translates to NULL in the database. I do not see anything in your code that requires the user to be logged in.
it was an issue with unicode method in the Profile model
and since, the balance was default null

Django_norel error 'DatabaseWrapper' object has no attribute 'operators' appengine

I'm using django_norel and followed all the install directions but I get this error:
Exception Value:
'DatabaseWrapper' object has no attribute 'operators'
when I go to the following view (return a JSON object of nicknames):
def listUsers(request, thread_id):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
else:
thread_user_list = UserProfile.objects.filter(user=UsersThreads.objects.filter(thread=thread_id).values('pk'))
data = serializers.serialize( 'json', thread_user_list, ensure_ascii=False, fields=('nickname'))
return HttpResponse(data)
All I'm trying to do is send a JSON object of a thread's users.
It's definitely related to the filter because I tried simply returning HttpResponse("asdf") and that worked. So I'm guessing it's a problem with Joining and norel databases. This code has worked when I was running on the sqlite database (maybe the filter function changed a bit while debugging).
Here are my models:
class UserProfile(models.Model):
nickname = models.CharField(max_length=25)
user = models.ForeignKey(User, unique=True)
facebook_id = models.CharField(max_length=200)
def __unicode__(self):
return self.nickname
class Thread(models.Model):
name = models.CharField(max_length=200)
tagline = models.CharField(max_length=200)
founder = models.ForeignKey(UserProfile)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.name
class UsersThreads(models.Model):
thread = models.ForeignKey(Thread)
user = models.ForeignKey(UserProfile)
def __unicode__(self):
return self.thread.name
I created UsersThreads because I was trying to avoid the google-app-engine not letting you do joins. I'm a confused about the need for django_norel.
Here's the python error code:
Environment:
Request Method: GET
Request URL: http://localhost:8000/users/4/
Django Version: 1.3
Python Version: 2.5.1
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'djangotoolbox',
'dbindexer',
'djangoappengine']
Installed Middleware:
('dbindexer.middleware.DBIndexerMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/Users/asdf/threadchat_main/django/core/handlers/base.py" in get_response
111.response = callback(request, *callback_args, **callback_kwargs)
File "/Users/asdf/threadchat_main/threadchat/views.py" in listUsers
162. data = serializers.serialize( 'json', thread_user_list, ensure_ascii=False, fields=('nickname'))
File "/Users/asdf/threadchat_main/django/core/serializers/__init__.py" in serialize
91. s.serialize(queryset, **options)
File "/Users/asdf/threadchat_main/django/core/serializers/base.py" in serialize
39. for obj in queryset:
File "/Users/asdf/threadchat_main/django/db/models/query.py" in _result_iter
107. self._fill_cache()
File "/Users/asdf/threadchat_main/django/db/models/query.py" in _fill_cache
774. self._result_cache.append(self._iter.next())
File "/Users/asdf/threadchat_main/django/db/models/query.py" in iterator
275. for row in compiler.results_iter():
File "/Users/asdf/threadchat_main/djangotoolbox/db/basecompiler.py" in results_iter
219. for entity in self.build_query(fields).fetch(low_mark, high_mark):
File "/Users/asdf/threadchat_main/djangotoolbox/db/basecompiler.py" in build_query
278. query.add_filters(self.query.where)
File "/Users/asdf/threadchat_main/djangotoolbox/db/basecompiler.py" in add_filters
73. self.add_filters(child)
File "/Users/asdf/threadchat_main/djangotoolbox/db/basecompiler.py" in add_filters
76. column, lookup_type, db_type, value = self._decode_child(child)
File "/Users/asdf/threadchat_main/djangotoolbox/db/basecompiler.py" in _decode_child
87. packed, value = constraint.process(lookup_type, value, self.connection)
File "/Users/asdf/threadchat_main/django/db/models/sql/where.py" in process
329. connection=connection, prepared=True)
File "/Users/asdf/threadchat_main/django/db/models/fields/subclassing.py" in inner
53. return func(*args, **kwargs)
File "/Users/asdf/threadchat_main/django/db/models/fields/related.py" in get_db_prep_lookup
156. sql, params = value._as_sql(connection=connection)
File "/Users/asdf/threadchat_main/django/db/models/query.py" in _as_sql
941. return obj.query.get_compiler(connection=connection).as_nested_sql()
File "/Users/asdf/threadchat_main/django/db/models/sql/compiler.py" in as_nested_sql
136. return obj.get_compiler(connection=self.connection).as_sql()
File "/Users/asdf/threadchat_main/django/db/models/sql/compiler.py" in as_sql
68. where, w_params = self.query.where.as_sql(qn=qn, connection=self.connection)
File "/Users/asdf/threadchat_main/django/db/models/sql/where.py" in as_sql
92. sql, params = child.as_sql(qn=qn, connection=connection)
File "/Users/asdf/threadchat_main/django/db/models/sql/where.py" in as_sql
95. sql, params = self.make_atom(child, qn, connection)
File "/Users/asdf/threadchat_main/django/db/models/sql/where.py" in make_atom
171. if lookup_type in connection.operators:
File "/Users/asdf/threadchat_main/dbindexer/base.py" in __getattr__
9. return getattr(self._target, name)
File "/Users/asdf/threadchat_main/django/utils/_threading_local.py" in __getattribute__
183. return object.__getattribute__(self, name)
Exception Type: AttributeError at /users/4/
Exception Value: 'DatabaseWrapper' object has no attribute 'operators'
Not sure if it is your install. I am getting the same problem when I try to do a django-nonrel "join". Maybe you can start by simplifying the code of thread_user_list by first getting the primary keys and confirming that your request is correct.