Django REST framework IntegerField max_length issue - django

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

Related

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

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.

"<Association: >" needs to have a value for field "association" before this many-to-many relationship can be used: django error

I have seen a bit of similar threads here in SO but cant seem to solve it. Here is my model:
class Association(models.Model):
'''
For members declared as groups
'''
member=models.ManyToManyField(User,related_name='association_user')
name=models.CharField(max_length=50)
def __str__(self):
return self.name
class Meta:
ordering=('name',)
The many-to-many relationship ended up creating, i think, a table under the hood with the following definitions:
association_id
user_id
I don't know if it is refering to the that field association nor how to add values to that table from my views.
my forms.py
class NewAssocationForm(forms.ModelForm):
'''
this is used to create a new form
'''
class Meta:
model=Association
fields=['name',]
labels=['Assocation Name'),]
and my views.py:
#login_required
def make_new(request):
'''
Register a new association or corporate
'''
if request.method=='POST':
form=NewAssocationForm(request.POST or None)
if form.is_valid():
new_association=form.save(commit=False)
new_association.member=request.user
new_association.save()
#add a message then redirect
return HttpResponseRedirect('/corporates/done/)
else:
form=NewAssocationForm(request.POST or None)
else:
form=NewAssocationForm(request.POST or None)
return render(request, "association_new.html", locals())
I don't have a field named association in my model at all. I doubt it is constraint erorr cos i can insert records to the table from the shell without any issues.
Here is my traceback.
Environment:
Request Method: POST
Request URL: http://localhost:9000/corporates/new/
Django Version: 1.10
Python Version: 3.4.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'widget_tweaks',
'welcome',
'members',
'corporates']
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 "D:\pyworks\agrigo\env\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "D:\pyworks\agrigo\env\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "D:\pyworks\agrigo\env\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\pyworks\agrigo\env\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "D:\pyworks\agrigo\env\agrigo\corporates\views.py" in make_new
78. new_association.member=request.user
File "D:\pyworks\agrigo\env\lib\site-packages\django\db\models\fields\related_descriptors.py" in __set__
499. manager = self.__get__(instance)
File "D:\pyworks\agrigo\env\lib\site-packages\django\db\models\fields\related_descriptors.py" in __get__
476. return self.related_manager_cls(instance)
File "D:\pyworks\agrigo\env\lib\site-packages\django\db\models\fields\related_descriptors.py" in __init__
783. (instance, self.source_field_name))
Exception Type: ValueError at /corporates/new/
Exception Value: "<Association: North Side>" needs to have a value for field "association" before this many-to-many relationship can be used.
Thanks for anyone who went through the long post. Apparently, I shouldn't specify user. So, deleting the line:
new_association.member=request.user
solved the issue. Makes sense; dumb me.

'str' object is not callable - SuccessMessageMixin

I get this error in a project whith SuccessMessageMixin and and not know why. This is my code in view.py.
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic import CreateView
class CampanaNueva(SuccessMessageMixin, CreateView):
model = Campana
template_name = "licencias_campana_nueva.html"
fields = ['temporada', 'descripcion']
success_message = "a"
And Raise this error on save:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/licencias/editar/1
Django Version: 1.9.4
Python Version: 3.4.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap3',
'home',
'widget_tweaks',
'socios',
'equipaciones',
'licencias']
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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'cc_corbelo.middleware.LoginRequiredMiddleware']
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\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\edit.py" in post
279. return super(BaseUpdateView, self).post(request, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\views\generic\edit.py" in post
222. return self.form_valid(form)
File "C:\Python34\lib\site-packages\django\contrib\messages\views.py" in form_valid
14. messages.success(self.request, success_message)
Exception Type: TypeError at /licencias/editar/1
Exception Value: 'str' object is not callable
I have this function working in another project without problems...
I got exactly this same message when I accidentally used the messages framework incorrectly in the form_valid method of a completely different view in my project.
The correct code should have been:
messages.success(request, "Deactivated product")
But what I had written instead was
messages.success = "Deactivated product"
This code doesn't work, but it doesn't cause an error on the page, either! However, as soon as I submitted a different form that used the SuccessMessageMixin, I would see the 'str' object is not callable error.
(Having a problem on one page cause an error on a completely different page was fun to debug.)

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.

userprofile matching query does not exist django facebook error

I am getting the following error after integrating
DoesNotExist at /facebook/connect/
UserProfile matching query does not exist.
Here is my models.py
from django.db import models
from django_facebook.models import FacebookProfileModel
from django.contrib.auth.models import User
class UserProfile(FacebookProfileModel):
user = models.OneToOneField(User)
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
profile, new = UserProfile.objects.get_or_create(user=instance)
ALSO IN MY SETTINGS
AUTH_PROFILE_MODULE = 'kk.UserProfile'
PLEASE HELP!
EDIT
EDIT My traceback
Environment:
Request Method: POST
Request URL: http://localhost:8000/facebook/connect/?facebook_login=1
Django Version: 1.4.2
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django_facebook',
'kk')
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 "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view
77. return view_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django_facebook-4.0.8-py2.7.egg/django_facebook/utils.py" in wrapper
358. response = f(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django_facebook-4.0.8-py2.7.egg/django_facebook/decorators.py" in _wrapped_view
89. get_persistent_graph(request, redirect_uri=current_uri)
File "/usr/local/lib/python2.7/dist-packages/django_facebook-4.0.8-py2.7.egg/django_facebook/api.py" in get_persistent_graph
61. graph = get_facebook_graph(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django_facebook-4.0.8-py2.7.egg/django_facebook/api.py" in get_facebook_graph
181. profile = request.user.get_profile()
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py" in get_profile
400. self._state.db).get(user__id__exact=self.id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in get
366. % self.model._meta.object_name)
Exception Type: DoesNotExist at /facebook/connect/
Exception Value: UserProfile matching query does not exist.
Either your create_profile signal isn't being fired (is the signal file being imported from somewhere in django machinery?)
Or you have existing users who have yet to run through your new create_profile signal handler.
Posting the traceback always helps.