Django templated mail 'dict' object has no attribute 'get_host' - python

I'm trying to send a verification email after a user registers an account using django-templated-mail.
This is the error I get after the user is created:
AttributeError 'dict' object has no attribute 'get_host'
So Django is trying to call get_host() and is unable to? So it's an error because it can't retrieve my host name?
Can someone point out what am I missing here?
class UserListView(generics.ListCreateAPIView):
serializer_class = UserSerializer
def perform_create(self, serializer):
user = serializer.save()
context = {'user': user}
to = user.email
email.ActivationEmail(context).send(to)
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'password', 'email')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
password = validated_data.pop('password')
user = super(UserSerializer, self).create(validated_data)
user.set_password(password)
user.save()
return user
class ActivationEmail(BaseEmailMessage):
template_name = 'email/activation.html'
def get_context_data(self):
context = super(ActivationEmail, self).get_context_data()
user = context.get('user')
context['uid'] = utils.encode_uid(user.pk)
context['token'] = default_token_generator.make_token(user)
context['url'] = 'verify/{uid}/{token}'.format(**context)
return context
Traceback:
Environment:
Request Method: POST
Request URL: http://localhost:8000/users/
Django Version: 2.0
Python Version: 3.6.6
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'templated_mail',
'accounts',]
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'simple_history.middleware.HistoryRequestMiddleware']
Traceback:
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
483. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
443. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
480. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/generics.py" in post
244. return self.create(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/rest_framework/mixins.py" in create
21. self.perform_create(serializer)
File "/code/accounts/views.py" in perform_create
54. email.ActivationEmail(context).send(to)
File "/usr/local/lib/python3.6/site-packages/templated_mail/mail.py" in send
69. self.render()
File "/usr/local/lib/python3.6/site-packages/templated_mail/mail.py" in render
61. context = make_context(self.get_context_data(), request=self.request)
File "/code/accounts/email.py" in get_context_data
12. context = super(ActivationEmail, self).get_context_data()
File "/usr/local/lib/python3.6/site-packages/templated_mail/mail.py" in get_context_data
33. site = get_current_site(self.request)
File "/usr/local/lib/python3.6/site-packages/django/contrib/sites/shortcuts.py" in get_current_site
16. return RequestSite(request)
File "/usr/local/lib/python3.6/site-packages/django/contrib/sites/requests.py" in __init__
10. self.domain = self.name = request.get_host()
Exception Type: AttributeError at /users/
Exception Value: 'dict' object has no attribute 'get_host'
Thank you much appreciate any help you may be able to render.

ActivationEmail takes the request as the first positional argument to its initializer. You're passing the context as the first positional argument, which causes ActivationEmail to fall over.
Make sure you pass the request instance as well as the context to ActivationEmail when you create it.
email.ActivationEmail(self.request, context).send(to)

You instantiated ActivationEmail incorrectly. The request parameter should be an HttpRequest object instead of a dict.

Related

Django Social Auth - Google: AttributeError: 'NoneType' object has no attribute 'provider'

I am receiving this error when trying to login via google, I've tried just about everything I can think of and similar issues on SO don't seem to help. I have a custom user model setup as such:
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class Departments(models.Model):
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.name
class AlluredUser(AbstractUser):
departments = models.ManyToManyField(Departments)
def __str__(self):
return self.username
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import AlluredUser
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = AlluredUser
fields = ('username', 'email')
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = AlluredUser
fields = ('username', 'email')
Social Auth Pipeline
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.auth_allowed',
'social_core.pipeline.social_auth.social_user',
'social_core.pipeline.user.get_username',
'social_core.pipeline.social_auth.associate_by_email',
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details'
)
Error Traceback
AttributeError at /auth/complete/google-oauth2/
'NoneType' object has no attribute 'provider'
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/auth/complete/google-oauth2/?state=8XLcbxz6sPSPOwJfOIXWOud88UJ5YtL2&code=4/twHRVLHTMzBV99K-VvektvJfjGuJYGBvqi254dWTuA2dLmbNFw3fIp8l5pdYSqKK89ONPGrxInG39pH8Wf-fpas&scope=email%20profile%20https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/userinfo.email%20openid&authuser=0&hd=allured.com&session_state=2403f8348307b18b8ab460026d3c88b1b18d759f..5dbb&prompt=none
Django Version: 2.2.4
Python Version: 3.7.4
Installed Applications:
['user.apps.UserConfig',
'issue_tracker.apps.IssueTrackerConfig',
'ytd_reports.apps.YtdReportsConfig',
'stats.apps.StatsConfig',
'scheduler.apps.SchedulerConfig',
'submissions.apps.SubmissionsConfig',
'dash_app.apps.DashAppConfig',
'contact.apps.ContactConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.humanize',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'social_django']
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',
'social_django.middleware.SocialAuthExceptionMiddleware',
'dashboard.middleware.loginRequired.LoginRequiredMiddleware']
Traceback:
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\social_django\utils.py" in wrapper
49. return func(request, backend, *args, **kwargs)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\social_django\views.py" in complete
33. *args, **kwargs)
File "C:\Users\jsarko\AppData\Local\Programs\Python\Python37-32\lib\site-packages\social_core\actions.py" in do_complete
71. social_user.provider)
Exception Type: AttributeError at /auth/complete/google-oauth2/
Exception Value: 'NoneType' object has no attribute 'provider'
I'm guessing it has something to do with the custom user model I created since I didn't have this problem beforehand. Any help would be much appreciated.
The error on the link doesn't match what you mention in the title.
For the traceback, the solution is just to add this:
SESSION_COOKIE_SECURE = False

Django : 'unicode' object has no attribute 'get'

I had a problem with my Django program. I'm a beginner in Django, I was looking for an answer with different posts with the same error than mine but no success ...
Here's my traceback :
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/pod
Django Version: 1.11.2
Python Version: 2.7.13
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'labinit',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
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 "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\admin\Desktop\django_learneo3\Learneo\labinit\views.py" in groupe_pod
121. if form.is_valid():
File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
183. return self.is_bound and not self.errors
File "C:\Python27\lib\site-packages\django\forms\forms.py" in errors
175. self.full_clean()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
384. self._clean_fields()
File "C:\Python27\lib\site-packages\django\forms\forms.py" in _clean_fields
396. value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "C:\Python27\lib\site-packages\django\forms\widgets.py" in
value_from_datadict
639. getter = data.get
Exception Type: AttributeError at /pod
Exception Value: 'unicode' object has no attribute 'get'
This issue appears since I have changed my init fonction, for the form that I use in my view :
Forms:
class Groupe_Form(forms.ModelForm) :
def __init__(self, nom_groupe, *args, **kwargs):
super(Groupe_Form,self).__init__(*args, **kwargs)
self.fields['pod'].widget = forms.Select()
pod1 = Groupe.objects.filter(nom_groupe = nom_groupe).values_list('pod', flat = True)
pods = list(pod1)
self.fields['pod'].queryset = Pod.objects.filter(id__in=pods)
class Meta:
model = Groupe
fields = ['pod']
Views :
def groupe_pod(request):
global new_groupe
grp = new_groupe
form = forms.Groupe_Form(request.POST, grp)
if request.method == 'POST':
if form.is_valid():
print "form was valid"
data_groupe_pod = request.POST.get('grp_pod')
print "data_groupe :", data_groupe_pod
global new_cours
print new_cours
if new_cours == "ICND1":
return redirect('http://127.0.0.1:8000/icnd_1')
elif new_cours == "ICND2":
return redirect('http://127.0.0.1:8000/icnd_2')
else :
form = forms.Groupe_Form(new_groupe)
return render(request, 'pod.html', locals())
I've tried many things, I really don't know where is the problem in my Django code.
Your form's __init__ method is:
def __init__(self, nom_groupe, *args, **kwargs):
Therefore you should instantiate it with:
form = forms.Groupe_Form(grp, request.POST)
You currently have the arguments the other way round.
Your __init__ signature has as its first parameter nom_groupe. In form = forms.Groupe_Form(request.POST, grp) you pass request.POST as the first parameter. You have to switch the parameters:
form = forms.Groupe_Form(grp, request.POST)

Django - one to one serializer Create function

I extended the default User model to ExtendedUser:
from django.db import models
from django.contrib.auth.models import User
class ExtendedUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
shirt_size = models.CharField(max_length=2)
User serializer:
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups', 'is_staff')
ExtendedUser serializer:
from api.resources.users.models.extended_user import ExtendedUser
from rest_framework import serializers
from django.contrib.auth.models import User
from api.resources.users.serializers.user import UserSerializer
class ExtendedUserSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer(read_only=False)
class Meta:
model = ExtendedUser
fields = ('url', 'shirt_size', 'user')
def create(self, validated_data):
user_data = validated_data.pop('user')
user = User.objects.create(**user_data)
return ExtendedUser.objects.create(user=user, **validated_data)
The main result should be that on submitting new ExtendedUser it will create a user too with one to one realation.
But I am getting this error:
User: myusername needs to have a value for field "user" before this
many-to-many relationship can be used.
Traceback:
Environment:
Request Method: POST
Request URL: http://localhost:8000/users/
Django Version: 1.10.4
Python Version: 2.7.12
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'api']
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 "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "C:\Python27\lib\site-packages\rest_framework\viewsets.py" in view
83. return self.dispatch(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch
477. response = self.handle_exception(exc)
File "C:\Python27\lib\site-packages\rest_framework\views.py" in handle_exception
437. self.raise_uncaught_exception(exc)
File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch
474. response = handler(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\rest_framework\mixins.py" in create
21. self.perform_create(serializer)
File "C:\Python27\lib\site-packages\rest_framework\mixins.py" in perform_create
26. serializer.save()
File "C:\Python27\lib\site-packages\rest_framework\serializers.py" in save
214. self.instance = self.create(validated_data)
File "C:/Users/ozbar/PycharmProjects/usnccm/usnccm-api\api\resources\users\serializers\extended_user.py" in create
15. user = User.objects.create(**user_data)
File "C:\Python27\lib\site-packages\django\db\models\manager.py" in manager_method
85. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in create
397. obj = self.model(**kwargs)
File "C:\Python27\lib\site-packages\django\contrib\auth\base_user.py" in __init__
68. super(AbstractBaseUser, self).__init__(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\base.py" in __init__
550. setattr(self, prop, kwargs[prop])
File "C:\Python27\lib\site-packages\django\db\models\fields\related_descriptors.py" in __set__
499. manager = self.__get__(instance)
File "C:\Python27\lib\site-packages\django\db\models\fields\related_descriptors.py" in __get__
476. return self.related_manager_cls(instance)
File "C:\Python27\lib\site-packages\django\db\models\fields\related_descriptors.py" in __init__
783. (instance, self.source_field_name))
Exception Type: ValueError at /users/
Exception Value: "<User: oz>" needs to have a value for field "user" before this many-to-many relationship can be used.
Validated_data object`s value on POST via django-rest web view:
{u'user': OrderedDict([(u'username', u'oz'), (u'email', u'oz.barshalom#gmail.com'), (u'groups', []), (u'is_staff', True)]), u'shirt_size': u'm'}
Okay for starters, the problem has nothing to do with django-rest-framework or your python version.
It seems to be an issue with django==1.10 as I simply tried:
User.objects.create(user="hello", email="333.22#eewofw.com", groups=[], is_staff=False)
in django's shell and received the exact same error. However, if we try newer versions of django, the problem does not persist.
I have noticed that when installing django using this command:
pip install django
It will install django==1.10 and not the latest version. If you mistakenly installed this older version, I suggest to uninstall django and then install the latest version:
pip uninstall django
pip install django==1.9.12
When using django==1.9.12, you need to remove groups completely from your UserSerializer and not provide it when doing your POST.

Django rest framework one to one relation Update serializer

I'm a beginner to the Django Rest Frame work. I have a problem from a long period i try to find a solution through many forums but unfortunately i didn't succeed. hope you help me
models.py
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
class Account(models.Model):
my_user=models.OneToOneField(User,on_delete=models.CASCADE)
statut=models.CharField(max_length=80)
date=models.DateField(auto_now=True,auto_now_add=False)
def __unicode__(self):
return self.my_user.first_name
Now i want to update Account serilizer .
Serializers .py
class AccountUpdateSerializer(serializers.ModelSerializer):
username=serializers.CharField(source ='my_user.username')
class Meta:
model= Account
fields=['id','username','statut','date']
def update(self, instance, validated_data):
print(instance)
instance.statut = validated_data.get('statut', instance.statut)
instance.my_user.username=validated_data['username']
return instance
Trace Back:
Environment:
Request Method: PUT
Request URL: http://127.0.0.1:9000/api/account/edit/1/
Django Version: 1.9
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',
'rest_framework',
'project',
'sponsors',
'contacts',
'medias',
'conferencier',
'competition',
'poste',
'account']
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']
Traceback:
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
474. response = self.handle_exception(exc)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception
434. self.raise_uncaught_exception(exc)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
471. response = handler(request, *args, **kwargs)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/generics.py" in put
256. return self.update(request, *args, **kwargs)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/mixins.py" in update
70. self.perform_update(serializer)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/mixins.py" in perform_update
74. serializer.save()
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/serializers.py" in save
187. self.instance = self.update(self.instance, validated_data)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/rest_framework/serializers.py" in update
907. setattr(instance, attr, value)
File "/home/asus/Documents/Gsource/gsource/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py" in __set__
207. self.field.remote_field.model._meta.object_name,
Exception Type: ValueError at /api/account/edit/1/
Exception Value: Cannot assign "{u'username': u'kais'}": "Account.my_user" must be a "User" instance.
Your update method is not called, because it is a method of the meta class of the serializer (AccountUpdateSerializer.Meta), not the serializer class AccountUpdateSerializer itself.
Here is how it should look:
class AccountUpdateSerializer(serializers.ModelSerializer):
username=serializers.CharField(source ='my_user.username')
class Meta:
model= Account
fields=['id','username','statut','date']
def update(self, instance, validated_data):
print(instance)
instance.statut = validated_data.get('statut', instance.statut)
instance.my_user.username = validated_data['username']
return instance
(Or did you just post your code incorrectly?)

django when adding data from admin interface: TypeError at admin/... unicode object not callable

I'm getting an error when trying to save to the following model using the admin interface:
models.py
class Answer(models.Model):
a = models.TextField(primary_key=True)
gloss = models.TextField(blank=True)
clean = models.TextField(blank=True)
count = models.IntegerField(blank=True)
p = models.IntegerField(blank=True)
def __unicode__(self):
return u"%s" % self.a
class Meta:
db_table = u'answers'
here's the error message that shows up on the admin interface:
Environment:
Request Method: POST
Request URL: http://localhost:8000/admin/emotions/answer/add/
Django Version: 1.4 pre-alpha SVN-16322
Python Version: 2.6.2
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'emo20qBrowser.emotions']
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 "/home/abe/bin/django-trunk/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/abe/bin/django-trunk/django/contrib/admin/options.py" in wrapper
316. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/abe/bin/django-trunk/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/home/abe/bin/django-trunk/django/views/decorators/cache.py" in _wrapped_view_func
77. response = view_func(request, *args, **kwargs)
File "/home/abe/bin/django-trunk/django/contrib/admin/sites.py" in inner
196. return view(request, *args, **kwargs)
File "/home/abe/bin/django-trunk/django/utils/decorators.py" in _wrapper
25. return bound_func(*args, **kwargs)
File "/home/abe/bin/django-trunk/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/home/abe/bin/django-trunk/django/utils/decorators.py" in bound_func
21. return func(self, *args2, **kwargs2)
File "/home/abe/bin/django-trunk/django/db/transaction.py" in inner
211. return func(*args, **kwargs)
File "/home/abe/bin/django-trunk/django/contrib/admin/options.py" in add_view
871. if form.is_valid():
File "/home/abe/bin/django-trunk/django/forms/forms.py" in is_valid
121. return self.is_bound and not bool(self.errors)
File "/home/abe/bin/django-trunk/django/forms/forms.py" in _get_errors
112. self.full_clean()
File "/home/abe/bin/django-trunk/django/forms/forms.py" in full_clean
269. self._post_clean()
File "/home/abe/bin/django-trunk/django/forms/models.py" in _post_clean
331. self.instance.clean()
Exception Type: TypeError at /admin/emotions/answer/add/
Exception Value: 'unicode' object is not callable
Okay, I think I figured it out... I'm using a variable/column called "clean". Django's admin interface has a method called "clean()" also, which does some kind of validation. It appears that there was some kind of naming conflict so I changed the variable to name to "cleaned" and then to make sure that it knows what database field to use (I'm using a legacy/preexisting db), I added a db_column option:
cleaned = models.TextField(blank=True,db_column="clean")
It would have been nice to know that "clean" was a reserved identifier in django but at least I only wasted half a day on this django stuff which ostensibly makes database operations easier. To be fair, I just started django this morning and if I would have found and answer on stackoverflow it would have been a breeze to fix.
If anyone knows a better way to handle this, let me know...

Categories