I am building a website similar to a bartering website, but we are bartering Time,
I have a class Transaction, where it takes the "offer" value, deductions that value from the balance of the requesting user, and credits the value to the Offer'r.
Right now when I click on "Accept Offer" from my template I get this error
ofertoj_transaction.accepted_by may not be NULL
Stacktrace:
IntegrityError at /oferto/accept/
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/oferto/accept/?offer_id=1&creator=2
Django Version: 1.5.4
Python Version: 2.7.4
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.comments',
'django.contrib.sitemaps',
'zinnia',
'tagging',
'mptt',
'south',
'registration',
'blogs',
'turtle',
'ofertoj',
'petoj',
'x',
'profiles')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/views/generic/base.py" in dispatch
86. return handler(request, *args, **kwargs)
File "/home/talisman/projects/tempilo/ofertoj/views.py" in get
74. accepted_by=self.request.user.id
File "/home/talisman/projects/tempilo/ofertoj/models.py" in create
59. new_transaction.save()
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/base.py" in save
546. force_update=force_update, update_fields=update_fields)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/base.py" in save_base
650. result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/manager.py" in _insert
215. return insert_query(self.model, objs, fields, **kwargs)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/query.py" in insert_query
1675. return query.get_compiler(using=using).execute_sql(return_id)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/sql/compiler.py" in execute_sql
937. cursor.execute(sql, params)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/backends/util.py" in execute
41. return self.cursor.execute(sql, params)
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/backends/sqlite3/base.py" in execute
364. six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/backends/sqlite3/base.py" in execute
362. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /oferto/accept/
Exception Value: ofertoj_transaction.accepted_by may not be NULL
part of ofertoj.views.py
class TransactionView(TemplateView, LoginRequiredMixin):
template_name = "ofertoj/offer_accepted.html"
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
if self.request.GET.get("offer_id"):
oferto = Oferto.objects.get(id=self.request.GET.get("offer_id"))
if oferto.valid:
transaction = Transaction()
transaction.create(
creator=self.request.GET.get("creator"),
amount=oferto.time,
accepted_by=self.request.user.id
)
acceptor = Profile.objects.get(user=self.request.user)
acceptor.balance = acceptor.balance - oferto.time
acceptor.save()
# credit the coins to the creator
creator = Profile.objects.get(user=oferto.user)
creator.balance = creator.balance + oferto.time
creator.save()
else:
return HttpResponse("This offer is already accepted")
else:
raise Http404
return self.render_to_response(context)
Part of Ofertoj.models
class Transaction(models.Model):
creator = models.IntegerField()
amount = models.IntegerField()
accepted_by = models.IntegerField()
def __unicode__(self):
return self.id
def create(self, **kwargs):
new_transaction = Transaction(
creator = kwargs['creator'],
amount = kwargs['amount'],
accepted_by = kwargs['accepted_by']
)
new_transaction.save()
return
this line is highlited in the stacktrace
acceptor = Profile.objects.get(user=self.request.user)
ofertoj.urls
url(
regex=r"^accept/$",
view = TransactionView.as_view(),
name = "accept_offer"
),
part of my template
{% if oferto.valid and not oferto.user == request.user %}
Accept this Offer
{% endif %}
<br /><br />
Your ofertoj application is trying to store a Transaction object which has an accepted_by field which is NULL but your database schema does not allow this field to be NULL.
Check this code:
transaction.create(
creator=self.request.GET.get("creator"),
amount=oferto.time,
accepted_by=self.request.user.id
)
and the code of transaction.create.
One possibility: if your user is not logged in then self.request.user.id will be None, and this translates to NULL in the database. I do not see anything in your code that requires the user to be logged in.
it was an issue with unicode method in the Profile model
and since, the balance was default null
Related
I'll try to be as concise as possible.
Background
I have a model Person which has a ForeignKey to model Document. Each Person can only have one Document but, as you may already know, each Document can be linked to many Persons.
In the Document's Admin form I have the Persons associated to the Document displayed inline. I can edit, add or delete the Persons right there.
Problem
Following these steps I get the error:
I open the Admin edit form for a Document. Let's call it Document
A. This Document has two Persons associated, let's call them John
Doe and Jane Doe. You can see them there (inline) in the form and
the fields are editable, but I don't touch them.
I open another tab and go straight to the Persons list and delete
Jane Doe.
I get back to the first tab (the Document's edit form) and click on
"Save and continue editing".
The form is sent and I get a generic error at the top (something
like) "Please, fix the following errors". But the form shows no
errors (next to the fields) to correct and, obviously, the record
for Jane Doe isn't displayed.
I click again on "Save and continue editing" and when the form is
sent I get the error "MultiValueDictKeyError: "u'person_set-1-id'"".
Ideal solution
I'd like to be able to display a custom error in the middle stage (when the first error appears, after the first save), saying something like "A person associated with this Document was deleted while you were editing it". Also, preventing the final error is highly desirable.
Error dump
MultiValueDictKeyError at /admin/persons/document/1145/
"u'person_set-1-id'"
Request Method: POST
Request URL: http://localhost:8000/admin/persons/document/1145/
Django Version: 1.7.7
Exception Type: MultiValueDictKeyError
Exception Value:
"u'person_set-1-id'"
Exception Location: /__PATH__/local/lib/python2.7/site-packages/django/utils/datastructures.py in __getitem__, line 319
Python Executable: /__PATH__/bin/python
Python Version: 2.7.15
Python Path:
['/__PATH__/test/test/apps',
'/__PATH__/test',
'/__PATH__/lib/python2.7',
'/__PATH__/lib/python2.7/plat-x86_64-linux-gnu',
'/__PATH__/lib/python2.7/lib-tk',
'/__PATH__/lib/python2.7/lib-old',
'/__PATH__/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/__PATH__/local/lib/python2.7/site-packages',
'/__PATH__/src/django-smart-selects',
'/__PATH__/lib/python2.7/site-packages',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/local/lib/python2.7/site-packages/odf',
'/__PATH__/test']
Server time: Mar, 29 Ene 2019 11:52:18 -0300
Environment:
Request Method: POST
Request URL: http://localhost:8000/admin/persons/document/1145/
Django Version: 1.7.7
Python Version: 2.7.15
Installed Applications:
('salmonella',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'crispy_forms',
'test.apps.persons',
'captcha',
'django_countries',
'django_extensions',
'import_export',
'django_object_actions',
'widget_tweaks',
'smart_selects',
'daterange_filter',
'compressor',
'auditlog')
Installed Middleware:
('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',
'auditlog.middleware.AuditlogMiddleware')
Traceback:
File "/__PATH__/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
583. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
52. response = view_func(request, *args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
206. return view(request, *args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in change_view
1456. return self.changeform_view(request, object_id, form_url, extra_context)
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
29. return bound_func(*args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
105. response = view_func(request, *args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
25. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/__PATH__/local/lib/python2.7/site-packages/django/db/transaction.py" in inner
394. return func(*args, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in changeform_view
1403. if all_valid(formsets) and form_validated:
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in all_valid
438. if not formset.is_valid():
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in is_valid
303. self.errors
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in errors
277. self.full_clean()
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in full_clean
325. form = self.forms[i]
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/functional.py" in __get__
55. res = instance.__dict__[self.func.__name__] = self.func(instance)
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/formsets.py" in forms
141. forms = [self._construct_form(i) for i in xrange(self.total_form_count())]
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/models.py" in _construct_form
868. form = super(BaseInlineFormSet, self)._construct_form(i, **kwargs)
File "/__PATH__/local/lib/python2.7/site-packages/django/forms/models.py" in _construct_form
581. pk = self.data[pk_key]
File "/__PATH__/local/lib/python2.7/site-packages/django/utils/datastructures.py" in __getitem__
319. raise MultiValueDictKeyError(repr(key))
Exception Type: MultiValueDictKeyError at /admin/persons/document/1145/
Exception Value: "u'person_set-1-id'"
UPDATE
I'm adding the definitions for models Person and Document.
class Document(models.Model):
creation_date = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=300, null=True, blank=True)
class Person(models.Model):
first_name = models.CharField(max_length=300)
last_name = models.CharField(max_length=300)
email = models.EmailField(max_length=300)
document = models.ForeignKey(Document)
UPDATE 2
One important thing I noticed is that, in the first error page (after the first submission of Document A form) the hidden inputs like person_set-TOTAL_FORMS and person_set-INITIAL_FORMS are set to 2 while they should be set to 1 (the actual number of persons). Obviously this happens because the submitted data doesn't reflect the actual database state.
I have this Serializer class for my User model:
serializers.py
class UserCreateSerializer(serializers.ModelSerializer):
"""User django serilization"""
key = serializers.StringRelatedField(source='key.token', read_only=True)
class Meta:
model = User
fields = ['phonenumber','id','email', 'username', 'key' ]
def create(self, validate_data):
user = User(**validate_data)
user.save()
return user
and this views.py
class UserListView(ListAPIView):
'''listing all users'''
permission_classes = (AllowAny,)
pagination_class = SmallPagination
throttle_classes = (UserRateThrottle, AnonRateThrottle,)
serializer_class = UserCreateSerializer
queryset = User.objects.all()
filter_backends = (filters.SearchFilter,)
search_fields = ('username', 'phonenumber', 'email')
I include 'rest_framework.authtoken', in my settings.py
and made a signal for Tokens from django Restframe work documentation.
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
urls.py
urlpatterns = [
re_path(r'^users/$', views.UserListView.as_view(), name='user-list'),]
so when I try to load my users List this error occurs :
'NoneType' object has no attribute 'token'
for attr in attrs:
try:
if isinstance(instance, collections.Mapping):
instance = instance[attr]
else:
instance = getattr(instance, attr) ...
except ObjectDoesNotExist:
return None
if is_simple_callable(instance):
try:
instance = instance()
except (AttributeError, KeyError) as exc:
....
the error location is from :
/backend/env/lib/python3.6/site-packages/rest_framework/fields.py in
get_attribute
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/api/users/create/
Django Version: 2.0
Python Version: 3.6.3
Installed Applications:
['django.contrib.admin',
'main.apps.MainConfig',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'stdimage',
'rest_framework.authtoken',
'blog',
'taggit',
'taggit_serializer',
'django.contrib.sites',
'corsheaders',
'webpack_loader']
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 "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
494. response = self.handle_exception(exc)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
454. self.raise_uncaught_exception(exc)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
491. response = handler(request, *args, **kwargs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/generics.py" in post
192. return self.create(request, *args, **kwargs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/mixins.py" in create
22. headers = self.get_success_headers(serializer.data)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/serializers.py" in data
537. ret = super(Serializer, self).data
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/serializers.py" in data
262. self._data = self.to_representation(self.instance)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/serializers.py" in to_representation
491. attribute = field.get_attribute(instance)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/relations.py" in get_attribute
177. return get_attribute(instance, self.source_attrs)
File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/fields.py" in get_attribute
100. instance = getattr(instance, attr)
Exception Type: AttributeError at /api/users/create/
Exception Value: 'NoneType' object has no attribute 'token'
authtoken model has related_name=auth_token to user models. So if you need to get token from user you should use auth_token.key:
key = serializers.StringRelatedField(source='auth_token.token', read_only=True)
I also got stuck in this error. But luckily i found the mistake i was doing.
I know its already been some time now. Still answering this question for newbies stuck in such silly error.
If we have to use Token model we have to mention the same in Installed Apps in settings.py file
'rest_framework.authtoken'
After that do migrate and you will see creation of new tables in the db.
Afterwards you can query the database like this...
Token.objects.all()
and you are good to go now.
Happy coding.
Please help me make REST social connect for provider Vkontakte.
I'm using django-allauth library (https://github.com/pennersr/django-allauth).
And django-rest-auth for REST auth (https://github.com/Tivix/django-rest-auth).
I've already have VKOAuth2Serializer that works fine for login and register.
But connect doesnt' work.
Here is urls:
url(r'^rest-auth/vk/connect/$', views.VkConnect.as_view(), name='vk_connect'),
url(r'^rest-auth/vk/', views.VkLogin.as_view()),
Views:
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from allauth.socialaccount.providers.vk.views import VKOAuth2Adapter
class VkLogin(CustomSocialLoginView):
adapter_class = VKOAuth2Adapter
serializer_class = VKOAuth2Serializer
client_class = OAuth2Client
callback_url = 'http://localhost:3000'
class VkConnect(SocialConnectView):
adapter_class = VKOAuth2Adapter
#May be here should be something else?
Serializer:
from allauth.socialaccount.helpers import complete_social_login
from rest_auth.registration.serializers import SocialLoginSerializer
from django.utils.translation import ugettext_lazy as _
from requests.exceptions import HTTPError
from rest_framework import serializers
class VKOAuth2Serializer(SocialLoginSerializer):
email = serializers.CharField(required=False, allow_blank=True)
user_id = serializers.CharField(required=False, allow_blank=True)
def validate(self, attrs):
view = self.context.get('view')
request = self._get_request()
if not view:
raise serializers.ValidationError(_("View is not defined, pass it as a context variable"))
adapter_class = getattr(view, 'adapter_class', None)
if not adapter_class:
raise serializers.ValidationError(_("Define adapter_class in view"))
adapter = adapter_class(request)
app = adapter.get_provider().get_app(request)
# Case 1: We received the access_token
if attrs.get('access_token'):
if not attrs.get('user_id') or not attrs.get('email'):
raise serializers.ValidationError(_("Incorrect input. email and user_id is required with access_token."))
access_data = {
'access_token': attrs.get('access_token'),
'user_id': attrs.get('user_id'),
'email': attrs.get('email'),
}
# Case 2: We received the authorization code
elif attrs.get('code'):
self.callback_url = getattr(view, 'callback_url', None)
self.client_class = getattr(view, 'client_class', None)
if not self.callback_url:
raise serializers.ValidationError(_("Define callback_url in view"))
if not self.client_class:
raise serializers.ValidationError(_("Define client_class in view"))
code = attrs.get('code')
provider = adapter.get_provider()
scope = provider.get_scope(request)
client = self.client_class(
request,
app.client_id,
app.secret,
adapter.access_token_method,
adapter.access_token_url,
self.callback_url,
scope
)
access_data = client.get_access_token(code)
if attrs.get('email'):
access_data['email'] = attrs.get('email')
if not access_data.get('email'):
raise serializers.ValidationError(_("Incorrect input. Social account must have email, otherwise send it in email field."))
else:
raise serializers.ValidationError(_("Incorrect input. access_token or code is required."))
social_token = adapter.parse_token({'access_token': access_data['access_token']})
social_token.app = app
try:
login = self.get_social_login(adapter, app, social_token, access_data)
complete_social_login(request, login)
except HTTPError:
raise serializers.ValidationError(_('Incorrect value'))
if not login.is_existing:
login.lookup()
login.save(request, connect=True)
attrs['user'] = login.account.user
return attrs
And here is view for registration/login and urls that works fine:
Please help me make REST connect for Vkontakte.
the project is here:
https://github.com/taime/imetrics
When trying to connect VK - I get error:
Environment:
Request Method: POST
Request URL: http://localhost:8000/rest-auth/vk/connect/
Django Version: 2.0.3
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_filters',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'django.contrib.sites',
'allauth',
'allauth.account',
'rest_auth.registration',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.vk',
'allauth.socialaccount.providers.twitter',
'storages',
'core',
'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 "/Users/tema/Sites/instametrics/.venv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/Users/tema/Sites/instametrics/.venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/Users/tema/Sites/instametrics/.venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/tema/Sites/instametrics/.venv/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/Users/tema/Sites/instametrics/.venv/lib/python3.5/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/Users/tema/Sites/instametrics/.venv/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper
62. return bound_func(*args, **kwargs)
File "/Users/tema/Sites/instametrics/.venv/lib/python3.5/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
76. return view(request, *args, **kwargs)
File "/Users/tema/Sites/instametrics/.venv/lib/python3.5/site-packages/django/utils/decorators.py" in bound_func
58. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/Users/tema/Sites/instametrics/.venv/lib/python3.5/site-packages/rest_auth/views.py" in dispatch
49. return super(LoginView, self).dispatch(*args, **kwargs)
File "/Users/tema/Sites/instametrics/.venv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
494. response = self.handle_exception(exc)
File "/Users/tema/Sites/instametrics/.venv/lib/python3.5/site-packages/rest_framework/views.py" in handle_exception
454. self.raise_uncaught_exception(exc)
File "/Users/tema/Sites/instametrics/.venv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
491. response = handler(request, *args, **kwargs)
File "/Users/tema/Sites/instametrics/.venv/lib/python3.5/site-packages/rest_auth/views.py" in post
93. self.serializer.is_valid(raise_exception=True)
File "/Users/tema/Sites/instametrics/.venv/lib/python3.5/site-packages/rest_framework/serializers.py" in is_valid
236. self._validated_data = self.run_validation(self.initial_data)
File "/Users/tema/Sites/instametrics/.venv/lib/python3.5/site-packages/rest_framework/serializers.py" in run_validation
438. value = self.validate(value)
File "/Users/tema/Sites/instametrics/code/core/serializers.py" in validate
73. login = self.get_social_login(adapter, app, social_token, access_data)
File "/Users/tema/Sites/instametrics/.venv/lib/python3.5/site-packages/rest_auth/registration/serializers.py" in get_social_login
58. social_login = adapter.complete_login(request, app, token, response=response)
File "/Users/tema/Sites/instametrics/code/allauth/socialaccount/providers/vk/views.py" in complete_login
54. extra_data = resp.json()['response'][0]
Exception Type: KeyError at /rest-auth/vk/connect/
Exception Value: 'response'
Since VK requires custom provider logic, you need to use serializer with logic defined in VKOAuth2Serializer but with social login state process being set to connect. You can achieve it by creating a subclass of VKOAuth2Serializer with SocialConnectMixin.
So your new serializer and connect view would look the following way:
Serializer:
from rest_auth.registration.serializers import SocialConnectMixin
class VKOAuth2ConnectSerializer(SocialConnectMixin, VKOAuth2Serializer):
pass
View:
class VkConnect(SocialConnectView):
adapter_class = VKOAuth2Adapter
serializer_class = VKOAuth2ConnectSerializer
VK API version field is required now. You can rewrite VKOAuth2Adapter class from github repo
https://github.com/pennersr/django-allauth/blob/master/allauth/socialaccount/providers/vk/views.py
Man am passing these values from the function to the db model as :
function definition :
def send_as_notification_to(person , link_id , unique_content , which_app, notification_type ):
nc = NotificationContent.objects.create( link_id = link_id , unique_content = str(unique_content))
app_obj = MetaAppNames.objects.create(name = which_app)
nt = NotificationType.objects.create( type = notification_type , app = app_obj)
notification = Notification(person = person)
notification.content = nc
notification.notification_type = nt
notification.save()
nc.save()
app_obj.save()
nt.save()
Calling view :
def crave_form(request):
if request.method == 'POST':
form = IcraveForm(request.POST)
if form.is_valid():
crave = form.save(commit = False)
crave.person = request.user
send_as_notification_to('admin' ,crave.id , crave.person , 'icrave' , 'crave' )
crave.save()
else:
form = IcraveForm()
return render(request, 'icrave/form.html', { 'form' : form})
but it's giving me error as :
notification_notificationcontent.link_id may not be NULL
Traceback ::
Environment:
Request Method: POST
Request URL: http://localhost:8000/icrave/create/
Django Version: 1.3
Python Version: 2.7.1
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.comments',
'ec.kiosk',
'ec.chakra',
'ec.ajax',
'ec.broadcast',
'ec.connect',
'ec.seek',
'ec.feed',
'ec.ec_model',
'ec.info',
'ec.domains',
'ec.souk',
'ec.meta',
'ec.shastra',
'ec.chat',
'ec.log',
'ec.icrave',
'ec.notification',
'doj',
'django.contrib.admin']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Volumes/Disk2/workspace/ec/ec/icrave/views.py" in crave_form
15. send_as_notification_to('admin' ,crave.id , crave.person , 'icrave' , 'crave' )
File "/Volumes/Disk2/workspace/ec/ec/notification/api.py" in send_as_notification_to
6. nc = NotificationContent.objects.create( link_id = link_id , unique_content = str(unique_content))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/manager.py" in create
138. return self.get_query_set().create(**kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py" in create
360. obj.save(force_insert=True, using=self.db)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/base.py" in save
460. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/base.py" in save_base
553. result = manager._insert(values, return_id=update_pk, using=using)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/manager.py" in _insert
195. return insert_query(self.model, values, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py" in insert_query
1436. return query.get_compiler(using=using).execute_sql(return_id)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
791. cursor = super(SQLInsertCompiler, self).execute_sql(None)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
735. cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/util.py" in execute
34. return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py" in execute
234. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /icrave/create/
Exception Value: notification_notificationcontent.link_id may not be NULL
When you call your function, you haven't committed your object (crave) to the database. If it's got a database-generated identifier for the id property, this will still be null. And it's this id property value that it's trying to use for the link_id that it is complaining about.
You need to either stop specifying commit=False, or you need to call crave.save, before you call your function.
commit=False means that you haven't saved anything yet, which means that the model doesn't have a valid ID yet. Save for real first, then pass the ID of the updated model.
I'm using django_norel and followed all the install directions but I get this error:
Exception Value:
'DatabaseWrapper' object has no attribute 'operators'
when I go to the following view (return a JSON object of nicknames):
def listUsers(request, thread_id):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
else:
thread_user_list = UserProfile.objects.filter(user=UsersThreads.objects.filter(thread=thread_id).values('pk'))
data = serializers.serialize( 'json', thread_user_list, ensure_ascii=False, fields=('nickname'))
return HttpResponse(data)
All I'm trying to do is send a JSON object of a thread's users.
It's definitely related to the filter because I tried simply returning HttpResponse("asdf") and that worked. So I'm guessing it's a problem with Joining and norel databases. This code has worked when I was running on the sqlite database (maybe the filter function changed a bit while debugging).
Here are my models:
class UserProfile(models.Model):
nickname = models.CharField(max_length=25)
user = models.ForeignKey(User, unique=True)
facebook_id = models.CharField(max_length=200)
def __unicode__(self):
return self.nickname
class Thread(models.Model):
name = models.CharField(max_length=200)
tagline = models.CharField(max_length=200)
founder = models.ForeignKey(UserProfile)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.name
class UsersThreads(models.Model):
thread = models.ForeignKey(Thread)
user = models.ForeignKey(UserProfile)
def __unicode__(self):
return self.thread.name
I created UsersThreads because I was trying to avoid the google-app-engine not letting you do joins. I'm a confused about the need for django_norel.
Here's the python error code:
Environment:
Request Method: GET
Request URL: http://localhost:8000/users/4/
Django Version: 1.3
Python Version: 2.5.1
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'djangotoolbox',
'dbindexer',
'djangoappengine']
Installed Middleware:
('dbindexer.middleware.DBIndexerMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/Users/asdf/threadchat_main/django/core/handlers/base.py" in get_response
111.response = callback(request, *callback_args, **callback_kwargs)
File "/Users/asdf/threadchat_main/threadchat/views.py" in listUsers
162. data = serializers.serialize( 'json', thread_user_list, ensure_ascii=False, fields=('nickname'))
File "/Users/asdf/threadchat_main/django/core/serializers/__init__.py" in serialize
91. s.serialize(queryset, **options)
File "/Users/asdf/threadchat_main/django/core/serializers/base.py" in serialize
39. for obj in queryset:
File "/Users/asdf/threadchat_main/django/db/models/query.py" in _result_iter
107. self._fill_cache()
File "/Users/asdf/threadchat_main/django/db/models/query.py" in _fill_cache
774. self._result_cache.append(self._iter.next())
File "/Users/asdf/threadchat_main/django/db/models/query.py" in iterator
275. for row in compiler.results_iter():
File "/Users/asdf/threadchat_main/djangotoolbox/db/basecompiler.py" in results_iter
219. for entity in self.build_query(fields).fetch(low_mark, high_mark):
File "/Users/asdf/threadchat_main/djangotoolbox/db/basecompiler.py" in build_query
278. query.add_filters(self.query.where)
File "/Users/asdf/threadchat_main/djangotoolbox/db/basecompiler.py" in add_filters
73. self.add_filters(child)
File "/Users/asdf/threadchat_main/djangotoolbox/db/basecompiler.py" in add_filters
76. column, lookup_type, db_type, value = self._decode_child(child)
File "/Users/asdf/threadchat_main/djangotoolbox/db/basecompiler.py" in _decode_child
87. packed, value = constraint.process(lookup_type, value, self.connection)
File "/Users/asdf/threadchat_main/django/db/models/sql/where.py" in process
329. connection=connection, prepared=True)
File "/Users/asdf/threadchat_main/django/db/models/fields/subclassing.py" in inner
53. return func(*args, **kwargs)
File "/Users/asdf/threadchat_main/django/db/models/fields/related.py" in get_db_prep_lookup
156. sql, params = value._as_sql(connection=connection)
File "/Users/asdf/threadchat_main/django/db/models/query.py" in _as_sql
941. return obj.query.get_compiler(connection=connection).as_nested_sql()
File "/Users/asdf/threadchat_main/django/db/models/sql/compiler.py" in as_nested_sql
136. return obj.get_compiler(connection=self.connection).as_sql()
File "/Users/asdf/threadchat_main/django/db/models/sql/compiler.py" in as_sql
68. where, w_params = self.query.where.as_sql(qn=qn, connection=self.connection)
File "/Users/asdf/threadchat_main/django/db/models/sql/where.py" in as_sql
92. sql, params = child.as_sql(qn=qn, connection=connection)
File "/Users/asdf/threadchat_main/django/db/models/sql/where.py" in as_sql
95. sql, params = self.make_atom(child, qn, connection)
File "/Users/asdf/threadchat_main/django/db/models/sql/where.py" in make_atom
171. if lookup_type in connection.operators:
File "/Users/asdf/threadchat_main/dbindexer/base.py" in __getattr__
9. return getattr(self._target, name)
File "/Users/asdf/threadchat_main/django/utils/_threading_local.py" in __getattribute__
183. return object.__getattribute__(self, name)
Exception Type: AttributeError at /users/4/
Exception Value: 'DatabaseWrapper' object has no attribute 'operators'
Not sure if it is your install. I am getting the same problem when I try to do a django-nonrel "join". Maybe you can start by simplifying the code of thread_user_list by first getting the primary keys and confirming that your request is correct.