Django-notification invalid literal for int() with base 10 - django

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.

Related

iterator should return strings, not bytes (did you open the file in text mode?) while uploading csv in django

I want to upload csv file and store in database. when I click the submit button I get the following error
Environment:
Request Method: POST
Request URL: http://localhost:8000/csv
Django Version: 1.9
Python Version: 3.4.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'django.contrib.admindocs',
'world',
'pft',
'wms',
'djgeojson',
'html5',
'geoexplorer']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "C:\Python34\Lib\site-packages\django\bin\geodjango\pft\views.py" in add_multiple_accounts
95. csv_result, rows_error = utils.handle_uploaded_file(file, utils.account_valid_fields, utils.create_account_in_db)
File "C:\Python34\Lib\site-packages\django\bin\geodjango\pft\utils.py" in handle_uploaded_file
24. if not valid_fields_method(data.fieldnames):
File "C:\Python34\lib\csv.py" in fieldnames
96. self._fieldnames = next(self.reader)
Exception Type: Error at /csv
Exception Value: iterator should return strings, not bytes (did you open the file in text mode?)
my handle file upload function is below-utils.py
def handle_uploaded_file(file, valid_fields_method, record_creation_function):
file.seek(0)
sniffdialect = csv.reader(codecs.iterdecode(file, 'utf-8')
file.seek(0)
data = csv.DictReader(file, dialect=sniffdialect)
if not valid_fields_method(data.fieldnames):
return False, -1
result, rows_error = record_creation_function(data)
return result, rows_error
I'm using django 1.9 and python 3.4. Please help ! I'm struggling for past 2 days.
TL;DR:
Change this:
file.seek(0)
sniffdialect = csv.reader(codecs.iterdecode(file, 'utf-8')
file.seek(0)
data = csv.DictReader(file, dialect=sniffdialect)
To this:
file.seek(0)
data = csv.DictReader(codecs.iterdecode(file, 'utf-8'))
(By the way, I'd check if seek(0) is really needed.)
Explanation:
You have understood that you need to decode the contents from your file, which is correct. However, to do so, you are using dialect, which is wrong.
dialect is not meant for this kind of stuff. Also, it should be a name registered via csv.register_dialect(), not an arbitrary iterator. But anyhow, dialects can't help you here.
Instead, you should pass the decoded stream directly to DictReader.

Is it possible to parse excel files in the forms.py?

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.

Django REST framework IntegerField max_length issue

I am getting an "__init__() got an unexpected keyword argument 'max_length'" error for my model field of IntegerField with max_length. The stack trace is as follows:
Environment:
Request Method: GET
Request URL: http://localhost:8000/api/jmc/foundation/
Django Version: 1.7.1
Python Version: 2.7.8
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dajaxice',
'dajax',
'rest_framework',
'core',
'analytics',
'api')
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/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py" in dispatch
406. response = self.handle_exception(exc)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/views.py" in dispatch
403. response = handler(request, *args, **kwargs)
File "/home/dev/Documents/Program Codes/Python/Django/Hera/api/views.py" in get
17. return Response(serializer.data)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in data
547. ret = super(ListSerializer, self).data
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in data
174. self._data = self.to_representation(self.instance)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in to_representation
500. self.child.to_representation(item) for item in iterable
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in to_representation
382. fields = [field for field in self.fields.values() if not field.write_only]
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in fields
245. for key, value in self.get_fields().items():
File "/usr/local/lib/python2.7/dist-packages/rest_framework/serializers.py" in get_fields
911. ret[field_name] = field_cls(**kwargs)
File "/usr/local/lib/python2.7/dist-packages/rest_framework/fields.py" in __init__
597. super(IntegerField, self).__init__(**kwargs)
Exception Type: TypeError at /api/jmc/foundation/
Exception Value: __init__() got an unexpected keyword argument 'max_length'
You might want to use the MaxValueValidator with IntegerField instead of max_length.
from django.db import models
from django.core.validators import MaxValueValidator
class MyModel(models.Model):
number = models.IntegerField(validators=[MaxValueValidator(100)])
Looks like IntegerField in Django doesn't have an max_length option. The reason we don't get any error is because Django suppresses it and 'Django REST framework' doesn't. Just removing the max_length option will make it work again.
Contrary to popular belief and common sense, Django does support the max_length argument on the IntegerField as well as any other field. The error you are seeing here is a known issue with Django REST Framework that does not currently have a fix.
The easiest way to fix this in your serializers (until a fix is done in DRF) is to redefine the field on the serializer without the max_length argument.
class MySerializer(serializers.ModelSerializer):
int_field = serializers.IntegerField()

Type Error: character mapping must return integer, None or unicode

I am trying to fetch information from linkedin but I keep getting the following error?
I have searched around but the fix I saw was only for those getting the error when using djangopiston. Can anyone help me fix this?
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/jobs/1/match/
Django Version: 1.3.1
Python Version: 2.7.2
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.flatpages',
'django.contrib.admin',
'django.contrib.staticfiles',
'compress',
'south',
'filer',
'easy_thumbnails',
'registration',
'socialregistration',
'socialregistration.contrib.facebook',
'socialregistration.contrib.twitter',
'socialregistration.contrib.linkedin',
'socialregistration.contrib.openid',
'privatebeta',
'api',
'profiles',
'jobs',
'misc']
Installed Middleware:
('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',
'socialregistration.contrib.facebook.middleware.FacebookMiddleware',
'socialregistration.contrib.linkedin.middleware.LinkedInMiddleware',
'misc.middleware.SubdomainMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware')
Traceback:
File "/home/arlus/jobmatch/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/arlus/jobmatch/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
93. response = view_func(request, *args, **kwargs)
File "/home/arlus/jobmatch/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "jobs/views.py" in match
60. matches = linkedin_api.get_connections(fields=['headline', 'summary',]).encode('utf-8')
File "../lib/linkedin/linkedin.py" in get_connections
291. response = self._do_normal_query(raw_url)
File "../lib/linkedin/linkedin.py" in _do_normal_query
757. signature_dict, self._access_token_secret, method, update=False)
File "../lib/linkedin/linkedin.py" in _calc_signature
789. hashed = hmac.new(self._calc_key(token_secret), signature_base_string, sha)
File "/usr/lib/python2.7/hmac.py" in new
133. return HMAC(key, msg, digestmod)
File "/usr/lib/python2.7/hmac.py" in __init__
72. self.outer.update(key.translate(trans_5C))
Exception Type: TypeError at /jobs/1/match/
Exception Value: character mapping must return integer, None or unicode
Its hard to tell but somewhere, either in urls.py and views.py are matches you should check the type of object being passed. It may not have expected value.
For instance /jobs/1/match, 1 maybe expected to be int but turns out be be str.
maybe because the text is being entered as unicode, try key.encode.('UTF-8')

Django index error

Yesterday it worked fine when I ran the server but today I am getting this:
****Environment:
Request Method: GET
Request URL: http://192.168.2.206:8080/home/
Django Version: 1.1.1
Python Version: 2.6.5
Installed Applications:
['django.contrib.auth',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.markup',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.comments',
'mysite.registration',
'mysite.profiles',
'mysite.epw',
'mysite.remember_me',
'mysite.avatar',
'mysite.django_documents',
'mysite.inlines',
'mysite.blog',
'mysite.forum',
'tagging']
Installed Middleware:
('django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'mysite.remember_me.views.AutoLogout')
Traceback:
File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/pymodules/python2.6/django/views/decorators/cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "/usr/lib/pymodules/python2.6/django/utils/decorators.py" in _wrapped_view
48. response = view_func(request, *args, **kwargs)
File "/home/karthik/Desktop/EPW_LOCAL/mysite/../mysite/remember_me/views.py" in remember_me_login
81. result_of_update, result_of_category, result_of_cover, result_of_latest, result_of_block, result_of_footer, result_of_research = common_blocks()
File "/home/karthik/Desktop/EPW_LOCAL/mysite/../mysite/epw/views.py" in common_blocks
332. result_of_update = display_updated_date()
File "/home/karthik/Desktop/EPW_LOCAL/mysite/../mysite/epw/views.py" in display_updated_date
1357. updated_obj = pdf_database.objects.filter(updated_date__gte = previous_datetime, updated_date__lte = cur_datetime).order_by("-updated_date")[0]
File "/usr/lib/pymodules/python2.6/django/db/models/query.py" in __getitem__
159. return list(qs)[0]
**Exception Type: IndexError at /home/
Exception Value: list index out of range******
Your queryset has 0 results. specifically this one:
updated_obj = pdf_database.objects.filter(updated_date__gte = previous_datetime, updated_date__lte = cur_datetime).order_by("-updated_date")
yesterday its working fine when run server today i am getting like this
Add a new pdf_database object from the admin or console and this view should be back running fine like yesterday