'str' object is not callable - SuccessMessageMixin - django

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

Related

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

Django: 'NoneType' object has no attribute 'user'

I am using Django User model for one of the select field.
However i am not able to pass only users linked to a commmon organisation/company.
I have a onetoone profile linking for each user. This one to onetoone model is again linked to organisation model.
Now need a form where select field should have users linked to organisation model.
Here is my form.py:
class taskaddform(forms.ModelForm):
def __init__(self,user, *args, **kwargs):
self.user = kwargs.pop('user', None)
self.request = kwargs.pop('request', None)
super(taskaddform, self).__init__(*args, **kwargs)
self.fields["assigned_to"].queryset=User.objects.filter(company=self.request.user.company.entity)
class Meta:
model=tasktable
fields=('task','assigned_to','discription','documents',)
views.py:
#login_required
def taskadd(request):
if request.method=='POST':
form=taskaddform(request.POST,request.FILES,request.user)
if form.is_valid():
new_form=form.save(commit=False)
new_form.created_by=request.user
new_form.company=request.user.company.entity
new_form.save()
return HttpResponseRedirect(reverse('taskadd'),messages.add_message(request, messages.SUCCESS,'Task added succesfully.'))
else:
form=taskaddform(request.user)
return render(request,'taskadd.html',{'form':form})
Error Log:
Request Method: GET
Request URL: http://127.0.0.1:8000/task/taskadd/
Django Version: 1.10
Exception Type: AttributeError
Exception Value:
'NoneType' object has no attribute 'user'
traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/task/taskadd/
Django Version: 1.10
Python Version: 2.7.10
Installed Applications:
('invoice',
'support',
'task',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'widget_tweaks')
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',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/Users/pulkitsharma/Documents/workspace1/tiktant/task/views.py" in taskadd
38. form=taskaddform(request.user)
File "/Users/pulkitsharma/Documents/workspace1/tiktant/task/forms.py" in __init__
11. self.fields["assigned_to"].queryset=User.objects.filter(company=self.request.user.company.entity)
Exception Type: AttributeError at /task/taskadd/
Exception Value: 'NoneType' object has no attribute 'user'
Updated views.py.
#login_required
def taskadd(request):
if request.method=='POST':
form=taskaddform(request, request.POST,request.FILES,request.user)
if form.is_valid():
new_form=form.save(commit=False)
new_form.created_by=request.user
new_form.company=request.user.company.entity
new_form.save()
return HttpResponseRedirect(reverse('taskadd'),messages.add_message(request, messages.SUCCESS,'Task added succesfully.'))
else:
form=taskaddform(request)
return render(request,'taskadd.html',{'form':form})
and in your forms.py --
class taskaddform(forms.ModelForm):
def __init__(self, request, *args, **kwargs):
self.request = request
super(taskaddform, self).__init__(request, *args, **kwargs)
self.fields["assigned_to"].queryset=User.objects.filter(company=self.request.user.company.entity)

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

Django: dynamic success_url results in "'NoneType' object has no attribute 'find'"

I would like to redirect the success_url to the same form after the form was submitted and valid. Online I found a description of a solution, however this solution and my other code option generate the same error message.
Exception Value: 'NoneType' object has no attribute 'find'
urls.py
url(r'^pictures/(?P<id>\d+)/$', PictureUpload.as_view(), name='picture_upload'),
...
1st views.py option
copies the existing link path
class PictureUpload(FormView):
form_class = PictureForm
template_name = 'picture_upload.html'
def get_success_url(self):
success_url = lambda self: self.request.path
2nd views.py option
recreates the link path based on the reverse url plus the id
class PictureUpload(FormView):
form_class = PictureForm
template_name = 'picture_upload.html'
def get_success_url(self):
success_url = reverse('picture_upload',
kwargs={'id': self.kwargs.get('id', None)})
Both options end up in the same traceback.
Request Method: POST
Request URL: http://127.0.0.1:8000/pictures/2/
Django Version: 1.5.1
Python Version: 2.7.1
Installed Applications:
('django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.gis',
'django.contrib.humanize',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'picture',
'debug_toolbar')
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',
'debug_toolbar.middleware.DebugToolbarMiddleware')
Traceback:
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
86. return handler(request, *args, **kwargs)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/edit.py" in post
165. return self.form_valid(form)
File "/Users/Development/project/apps/picture/picture_views.py" in form_valid
180. return super(PictureUpload, self).form_valid(form)
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/views/generic/edit.py" in form_valid
65. return HttpResponseRedirect(self.get_success_url())
File "/Users/Development/virtual-re/lib/python2.7/site-packages/django/http/response.py" in __init__
388. parsed = urlparse(redirect_to)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urlparse.py" in urlparse
134. tuple = urlsplit(url, scheme, allow_fragments)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urlparse.py" in urlsplit
173. i = url.find(':')
Exception Type: AttributeError at /pictures/2/
Exception Value: 'NoneType' object has no attribute 'find'
It looks like neither of your get_success_url implementations actually return the URL, so assuming that's not just a cut-and-paste error you're passing None to the HttpResponseRedirect.

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.