Man am passing these values from the function to the db model as :
function definition :
def send_as_notification_to(person , link_id , unique_content , which_app, notification_type ):
nc = NotificationContent.objects.create( link_id = link_id , unique_content = str(unique_content))
app_obj = MetaAppNames.objects.create(name = which_app)
nt = NotificationType.objects.create( type = notification_type , app = app_obj)
notification = Notification(person = person)
notification.content = nc
notification.notification_type = nt
notification.save()
nc.save()
app_obj.save()
nt.save()
Calling view :
def crave_form(request):
if request.method == 'POST':
form = IcraveForm(request.POST)
if form.is_valid():
crave = form.save(commit = False)
crave.person = request.user
send_as_notification_to('admin' ,crave.id , crave.person , 'icrave' , 'crave' )
crave.save()
else:
form = IcraveForm()
return render(request, 'icrave/form.html', { 'form' : form})
but it's giving me error as :
notification_notificationcontent.link_id may not be NULL
Traceback ::
Environment:
Request Method: POST
Request URL: http://localhost:8000/icrave/create/
Django Version: 1.3
Python Version: 2.7.1
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.comments',
'ec.kiosk',
'ec.chakra',
'ec.ajax',
'ec.broadcast',
'ec.connect',
'ec.seek',
'ec.feed',
'ec.ec_model',
'ec.info',
'ec.domains',
'ec.souk',
'ec.meta',
'ec.shastra',
'ec.chat',
'ec.log',
'ec.icrave',
'ec.notification',
'doj',
'django.contrib.admin']
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')
Traceback:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Volumes/Disk2/workspace/ec/ec/icrave/views.py" in crave_form
15. send_as_notification_to('admin' ,crave.id , crave.person , 'icrave' , 'crave' )
File "/Volumes/Disk2/workspace/ec/ec/notification/api.py" in send_as_notification_to
6. nc = NotificationContent.objects.create( link_id = link_id , unique_content = str(unique_content))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/manager.py" in create
138. return self.get_query_set().create(**kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py" in create
360. obj.save(force_insert=True, using=self.db)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/base.py" in save
460. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/base.py" in save_base
553. result = manager._insert(values, return_id=update_pk, using=using)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/manager.py" in _insert
195. return insert_query(self.model, values, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py" in insert_query
1436. return query.get_compiler(using=using).execute_sql(return_id)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
791. cursor = super(SQLInsertCompiler, self).execute_sql(None)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
735. cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/util.py" in execute
34. return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py" in execute
234. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /icrave/create/
Exception Value: notification_notificationcontent.link_id may not be NULL
When you call your function, you haven't committed your object (crave) to the database. If it's got a database-generated identifier for the id property, this will still be null. And it's this id property value that it's trying to use for the link_id that it is complaining about.
You need to either stop specifying commit=False, or you need to call crave.save, before you call your function.
commit=False means that you haven't saved anything yet, which means that the model doesn't have a valid ID yet. Save for real first, then pass the ID of the updated model.
Related
I'm using django-notification to create notifications. based on it's documention I putted:
url(r'^inbox/notifications/', include(notifications.urls, namespace='notifications')),
in my urls.py. I generate a notification for test by using this in my views.py:
guy = User.objects.get(username = 'SirSaleh')
notify.send(sender=User, recipient=guy, verb='you visted the site!')
and I can easily get the number of unread notification in this url:
http://127.0.0.1:8000/inbox/notifications/api/unread_count/
it return {"unread_count": 1} as I want. but with /api/unread_list/ I can not to get the list of notifications and I get this error:
ValueError at /inbox/notifications/
invalid literal for int() with base 10: '<property object at 0x7fe1b56b6e08>'
As I beginner in using django-notifications any help will be appreciated.
Full TraceBack
Environment:
Request Method: GET Request URL:
http://127.0.0.1:8000/inbox/notifications/api/unread_list/
Django Version: 2.0.2 Python Version: 3.5.2 Installed Applications:
['django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles',
'django.contrib.sites', 'django.forms', 'rest_framework',
'allauth', 'allauth.account', 'allauth.socialaccount', 'guardian',
'axes', 'django_otp', 'django_otp.plugins.otp_static',
'django_otp.plugins.otp_totp', 'two_factor', 'invitations',
'avatar', 'imagekit', 'import_export', 'djmoney', 'captcha',
'dal', 'dal_select2', 'widget_tweaks', 'braces', 'django_tables2',
'phonenumber_field', 'hitcount', 'el_pagination',
'maintenance_mode', 'notifications', 'mathfilters',
'myproject_web', 'Order', 'PhotoGallery', 'Search', 'Social',
'UserAccount', 'UserAuthentication', 'UserAuthorization',
'UserProfile'] Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'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',
'django_otp.middleware.OTPMiddleware',
'maintenance_mode.middleware.MaintenanceModeMiddleware']
Traceback:
File
"/home/saleh/Projects/myproject_web/lib/python3.5/site-packages/django/core/handlers/exception.py"
in inner
35. response = get_response(request)
File
"/home/saleh/Projects/myproject_web/lib/python3.5/site-packages/django/core/handlers/base.py"
in _get_response
128. response = self.process_exception_by_middleware(e, request)
File
"/home/saleh/Projects/myproject_web/lib/python3.5/site-packages/django/core/handlers/base.py"
in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File
"/home/saleh/Projects/myproject_web/lib/python3.5/site-packages/notifications/views.py"
in live_unread_notification_list
164. if n.actor:
File
"/home/saleh/Projects/myproject_web/lib/python3.5/site-packages/django/contrib/contenttypes/fields.py"
in get
253. rel_obj = ct.get_object_for_this_type(pk=pk_val)
File
"/home/saleh/Projects/myproject_web/lib/python3.5/site-packages/django/contrib/contenttypes/models.py"
in get_object_for_this_type
169. return self.model_class()._base_manager.using(self._state.db).get(**kwargs)
File
"/home/saleh/Projects/myproject_web/lib/python3.5/site-packages/django/db/models/query.py"
in get
394. clone = self.filter(*args, **kwargs)
File
"/home/saleh/Projects/myproject_web/lib/python3.5/site-packages/django/db/models/query.py"
in filter
836. return self._filter_or_exclude(False, *args, **kwargs)
File
"/home/saleh/Projects/myproject_web/lib/python3.5/site-packages/django/db/models/query.py"
in _filter_or_exclude
854. clone.query.add_q(Q(*args, **kwargs))
File
"/home/saleh/Projects/myproject_web/lib/python3.5/site-packages/django/db/models/sql/query.py"
in add_q
1253. clause, _ = self._add_q(q_object, self.used_aliases)
File
"/home/saleh/Projects/myproject_web/lib/python3.5/site-packages/django/db/models/sql/query.py"
in _add_q
1277. split_subq=split_subq,
File
"/home/saleh/Projects/myproject_web/lib/python3.5/site-packages/django/db/models/sql/query.py"
in build_filter
1215. condition = self.build_lookup(lookups, col, value)
File
"/home/saleh/Projects/myproject_web/lib/python3.5/site-packages/django/db/models/sql/query.py"
in build_lookup
1085. lookup = lookup_class(lhs, rhs)
File
"/home/saleh/Projects/myproject_web/lib/python3.5/site-packages/django/db/models/lookups.py"
in init
18. self.rhs = self.get_prep_lookup()
File
"/home/saleh/Projects/myproject_web/lib/python3.5/site-packages/django/db/models/lookups.py"
in get_prep_lookup
68. return self.lhs.output_field.get_prep_value(self.rhs)
File
"/home/saleh/Projects/myproject_web/lib/python3.5/site-packages/django/db/models/fields/init.py"
in get_prep_value
947. return int(value)
Exception Type: ValueError at /inbox/notifications/api/unread_list/
Exception Value: invalid literal for int() with base 10: ''
The actor_object_id needs to be a CharField to support UUID based primary keys.
oops! It was my mistake.
I Finally find out what was the problem. actor_object_id was the field of notifications_notification table, which User.objects.get(username = 'SirSaleh') saved in it. It should be Interger (user_id of actor).
So I dropped previous table changed instance to User.objects.get(username = 'SirSaleh') to User ID. Problem solved.
So Why type of actor_object_id is CharField (varchar)? (at least I don't know) ;))
This is old, but I happen to know the answer.
In your code, you wrote:
guy = User.objects.get(username = 'SirSaleh')
notify.send(sender=User, recipient=guy, verb='you visted the site!')
You express that you want guy to be your sender However, in notify.send, you marked the sender as a generic User object, not guy.
So, change your code to:
guy = User.objects.get(username = 'SirSaleh')
notify.send(sender=guy, recipient=guy, verb='you visted the site!')
Notifications will take the user object guy, extrapolate the ID and store it in the database accordingly.
I'm trying to do validation of an uploaded excel file in forms.py. Is this even possible?
I'm getting this error message "coercing to Unicode: need string or buffer, NoneType found"
forms.py
from .parse_excel import *
class FileSurveyForm(forms.ModelForm):
file = forms.FileField()
....
def clean_file(self):
data_file = self.cleaned_data.get('file')
data = parse_file(data_file.read())
netmaskRegex = '^(((128|192|224|240|248|252|254)\.0\.0\.0)|(255\.(0|128|192|224|240|248|252|254)\.0\.0)|(255\.255\.(0|128|192|224|240|248|252|254)\.0)|(255\.255\.255\.(0|128|192|224|240|248|252|254)))$'
for order in data:
if re.match(netmaskRegex, order['netmask']) is not None:
raise ValidationError("Invalid netmask!")
return file
parse_excel.py
import xlrd
def parse_file(datafile):
workbook = xlrd.open_workbook(file_contents=datafile)
sheet = workbook.sheet_by_index(0)
START_ROW = 35
END_ROW = 60
myList = []
for row in range(START_ROW,END_ROW):
values = (sheet.row_values(row, start_colx=1, end_colx=20))
headers = ["controller", "hostname", "domain", "ip_address", "netmask", "gateway", "dns1", "dns2", "ntp1", "ntp2",
"order_name", "order_phone", "order_email",
"shipping_adress", "shipping_city", "shipping_region", "shipping_region_code", "shipping_country", "shipping_diff"]
dictionary = dict(zip(headers, values))
myList.append(dictionary)
return myList
stack trace added:
Environment:
Request Method: POST
Request URL: http://10.21.145.103:8000/cooking/survey/file_upload/
Django Version: 1.6.6
Python Version: 2.6.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.formtools',
'contact',
'cooking')
Installed Middleware:
('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 "/usr/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/views/generic/base.py" in dispatch
87. return handler(request, *args, **kwargs)
File "/home/jeremy.kwong/mysite/cooking/views.py" in post
101. if (form.is_valid() and ingredient_form.is_valid()):
File "/usr/lib/python2.6/site-packages/django/forms/forms.py" in is_valid
129. return self.is_bound and not bool(self.errors)
File "/usr/lib/python2.6/site-packages/django/forms/forms.py" in errors
121. self.full_clean()
File "/usr/lib/python2.6/site-packages/django/forms/forms.py" in full_clean
273. self._clean_fields()
File "/usr/lib/python2.6/site-packages/django/forms/forms.py" in _clean_fields
291. value = getattr(self, 'clean_%s' % name)()
File "/home/jeremy.kwong/mysite/cooking/forms.py" in clean_file
226. data = parse_file(data_file.read())
File "/home/jeremy.kwong/mysite/cooking/parse_excel.py" in parse_file
4. workbook = xlrd.open_workbook(file_contents=datafile)
File "/usr/lib/python2.6/site-packages/xlrd/__init__.py" in open_workbook
394. f = open(filename, "rb")
Exception Type: TypeError at /cooking/survey/file_upload/
Exception Value: coercing to Unicode: need string or buffer, NoneType found
This error occurs because file_contents argument of the xlrd.open_workbook() is empty.
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
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.
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.