I have 2 models in my django project. DB is mongoDB and I use Djongo.
Here are the models:
class Item(models.Model):
item_id = models.IntegerField(primary_key=True)
item_name = models.CharField(max_length=30)
def __str__(self):
return f'<{self.item_name}>'
class Items(models.Model):
items_id = models.IntegerField(primary_key=True)
inventory = models.ArrayField(model_container=Item,)
neutral_item = models.EmbeddedField(model_container=Item,)
buffs = models.ArrayField(model_container=Item,)
def __str__(self):
return f'<{self.inventory}, {self.neutral_item}>'
When I do:
item = Item(item_name='Helmet')
items = Items(inventory=[item])
I am getting this TypeError:
'Item' object is not subscriptable
What is wrong?
Whole error message:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/base.py", line 745, in save
self.save_base(using=using, force_insert=force_insert,
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/base.py", line 782, in save_base
updated = self._save_table(
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/base.py", line 887, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/base.py", line 924, in _do_insert
return manager._insert(
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1390, in execute_sql
for sql, params in self.as_sql():
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1333, in as_sql
value_rows = [
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1334, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1334, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1275, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/djongo/models/fields.py", line 215, in get_db_prep_save
return self.get_prep_value(value)
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/djongo/models/fields.py", line 222, in get_prep_value
processed_value = self._value_thru_fields('get_prep_value',
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/djongo/models/fields.py", line 315, in _value_thru_fields
post_dict = super()._value_thru_fields(func_name,
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/djongo/models/fields.py", line 145, in _value_thru_fields
field_value = value[field.attname]
TypeError: 'Item' object is not subscriptable
According to the Djongo docs for ArrayField you should instantiate like this:
entry = Entry()
entry.authors = [{'name': 'John', 'email': 'john#mail.com'},
{'name': 'Paul', 'email': 'paul#mail.com'}]
entry.save()
So in your case, you would do this.
items = Items()
items.inventory = [
{'item_name': 'Helmet'}
]
items.save()
Related
Hi there i am new ot django and django rest framework and i am having torouble when using serializers with PrimarayKeyTelatedFields() the code below is my code for my models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=50)
age = models.IntegerField(default=0)
class Book(models.Model):
name = models.CharField(max_length=40)
author = models.ForeignKey(to=Author, on_delete=models.CASCADE)
below is my serializer code
from rest_framework import serializers
from books.models import Book, Author
class BookSerializer(serializers.ModelSerializer):
author_id = serializers.PrimaryKeyRelatedField(many=False,
queryset=Author.objects.all())
class Meta:
model = Book
fields = ['id', 'name', 'author_id']
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = ['id', 'name', 'age']
and when i try to execute following commands in shell
>>from books.api.serializers import BookSerializer, AuthorSerializer
>> play1 = BookSerializer(data = { 'author_id':1 ,'name':'book1' })
>>play1.is_valid()
True
>>play1.save()
After executing above i got the huge error as i pasted below
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 962, in create
instance = ModelClass._default_manager.create(**validated_data)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 514, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 806, in save
self.save_base(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 857, in save_base
updated = self._save_table(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 1000, in _save_table
results = self._do_insert(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 1041, in _do_insert
return manager._insert(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 1434, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1620, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1547, in as_sql
value_rows = [
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1548, in <listcomp>
[
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1549, in <listcomp>
self.prepare_value(field, self.pre_save_val(field, obj))
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1487, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related.py", line 1126, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 910, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 2668, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1990, in get_prep_value
raise e.__class__(
TypeError: Field 'id' expected a number but got <Author: Author object (1)>.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 212, in save
self.instance = self.create(validated_data)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 981, in create
raise TypeError(msg)
TypeError: Got a `TypeError` when calling `Book.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Book.objects.create()`. You may need to make the field read-only, or override the BookSerializer.create() method to handle this correctly.
Original exception was:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 962, in create
instance = ModelClass._default_manager.create(**validated_data)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 514, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 806, in save
self.save_base(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 857, in save_base
updated = self._save_table(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 1000, in _save_table
results = self._do_insert(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 1041, in _do_insert
return manager._insert(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 1434, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1620, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1547, in as_sql
value_rows = [
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1548, in <listcomp>
[
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1549, in <listcomp>
self.prepare_value(field, self.pre_save_val(field, obj))
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1487, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related.py", line 1126, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 910, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 2668, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1990, in get_prep_value
raise e.__class__(
TypeError: Field 'id' expected a number but got <Author: Author object (1)>.
you passed here an object instead of id..
author_id = serializers.PrimaryKeyRelatedField(many=False,
queryset=Author.objects.all())
you should pass an id like this
author_id = serializers.PrimaryKeyRelatedField(many=False,
queryset=Author.objects.get(id=request.user.id))
Remember whatever you queried it should be an int value not str or object
Cause
The problem is caused by setting author_id with serializer.PrimaryKeyRelatedField
Explanation
Django will internally auto-create an attribute for related fields (ForeignKey, OneToOneField, ...) with the suffix _id appending to the declared field name. The data type of this field is a number. In this case, the author field in Book will have an attribute called author_id. The problem comes from serializer.PrimaryKeyRelatedField returning a model instance in the serializer's validated data, causing field author_id to be set with Author instance. Resulting in an error.
Solution
Rename author_id attribute to author.
class BookSerializer(serializers.ModelSerializer):
author = serializers.PrimaryKeyRelatedField(queryset=Author.objects.all())
class Meta:
model = Book
fields = ['id', 'name', 'author']
I am trying to implement bulk_create my inserting multiple objects in
a relation, not sure whether I am doing it right i have added trace back as well below is skill set model
class Skillset(models.Model):
skill_name = models.CharField(max_length=255)
def __str__(self):
return self.skill_name
my view
skill_name = request.POST.getlist('skill_name')
skill_level = request.POST.getlist('skill_level')
print(f'skill name-> {skill_name} skill level ->{skill_level}')
seeker_skll = []
# testing destructing
for skill_nme, skill_lvl in zip(skill_name, skill_level):
skill_set = Skillset.objects.get(skill_name=skill_nme)
seeker_skll.append(Seekerskillset(
skill_set=skill_set, skill_level=skill_lvl, seeker=user))
seeker_skll = Skillset.objects.bulk_create(seeker_skll)
print(seeker_skll)
return redirect('/users/dashboard')
Model
class Seekerskillset(models.Model):
skill_set = models.ForeignKey(Skillset, on_delete=models.CASCADE)
seeker = models.ForeignKey(SeekerProfile, on_delete=models.CASCADE)
skill_level = models.CharField(max_length=25)
class Meta:
verbose_name = 'Seeker skill set'
error i am getting
AttributeError: 'Seekerskillset' object has no attribute 'skill_name'
Traceback (most recent call last):
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\atif\PycharmProjects\my_proj\mysite_jobportal\seekerbuilder\views.py", line 43, in update_details
seeker_skll = Skillset.objects.bulk_create(seeker_skll)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 515, in bulk_create
objs_without_pk, fields, batch_size, ignore_conflicts=ignore_conflicts,
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1293, in _batched_insert
self._insert(item, fields=fields, using=self.db, ignore_conflicts=ignore_conflicts)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1270, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1415, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1360, in as_sql
for obj in self.query.objs
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1360, in <listcomp>
for obj in self.query.objs
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1359, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1310, in pre_save_val
return field.pre_save(obj, add=True)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\__init__.py", line 822, in pre_save
return getattr(model_instance, self.attname)
Exception Type: AttributeError at /users/app_det/
Exception Value: 'Seekerskillset' object has no attribute 'skill_name'
The problem is caused by using Skillset to bulk create Seekerskillset objects.
So change:
seeker_skll = Skillset.objects.bulk_create(seeker_skll)
to:
seeker_skll = Seekerskillset.objects.bulk_create(seeker_skll)
Hi guys i have this error when I'm trying to create or update the user model
the error is happening on the profile model
I'm using Django 2.1.7 with PostgreSQL
Internal Server Error: /accounts/update/
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\utils\dateparse.py", line 106, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or bytes-like object
Error Traceback
Internal Server Error: /accounts/update/
Traceback (most recent call last):
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "E:\practice my skills\fullStackDjangoAndReact\chatapp\accounts\api.py", line 73, in post
user = user_ser.save()
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\rest_framework\serializers.py", line 207, in save
self.instance = self.update(self.instance, validated_data)
File "E:\practice my skills\fullStackDjangoAndReact\chatapp\accounts\serializers.py", line 67, in update
profile.save()
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\base.py", line 718, in save
force_update=force_update, update_fields=update_fields)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\base.py", line 748, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\base.py", line 812, in _save_table
forced_update)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\base.py", line 861, in _do_update
return filtered._update(values) > 0
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\query.py", line 712, in _update
return query.get_compiler(self.db).execute_sql(CURSOR)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\sql\compiler.py", line 1383, in execute_sql
cursor = super().execute_sql(result_type)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\sql\compiler.py", line 1052, in execute_sql
sql, params = self.as_sql()
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\sql\compiler.py", line 1349, in as_sql
val = field.get_db_prep_save(val, connection=self.connection)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\fields\__init__.py", line 790, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\fields\__init__.py", line 1429, in get_db_prep_value
value = self.get_prep_value(value)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\fields\__init__.py", line 1408, in get_prep_value
value = super().get_prep_value(value)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\fields\__init__.py", line 1268, in get_prep_value
return self.to_python(value)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\db\models\fields\__init__.py", line 1369, in to_python
parsed = parse_datetime(value)
File "E:\PRACTI~1\FULLST~1\chatapp\env\lib\site-packages\django\utils\dateparse.py", line 106, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or bytes-like object
the Profile Model:
class Profile(models.Model):
user = models.OneToOneField(User ,on_delete=models.CASCADE)
icon = models.CharField(max_length=256)
active = models.BooleanField(default=False)
join_date = models.DateTimeField(default=timezone.now, blank=True, null=True)
born_date = models.DateTimeField(blank=True, null=True)
The Serializer
class UpdateUserSer(serializers.ModelSerializer):
profile = UpdateProfileSer()
class Meta:
model = User
fields = ("username","email","first_name","profile")
def update(self , instance , validated_data):
prfile_data = validated_data.pop("profile")
instance.username = validated_data.get("username" , instance.username)
instance.email = validated_data.get("email" , instance.email)
instance.first_name = validated_data.get("first_name" , instance.first_name)
instance.save()
profile = instance.profile
profile.icon = prfile_data.get("icon" ,profile.icon)
profile.save()
return instance
def validate(self , data):
user_instance = self.context["request"].user
user_email = data["email"]
users = User.objects.all()
if users.filter(email = user_email).exclude(id=user_instance.id).exists():
raise serializers.ValidationError("this email has been token choose another one please")
return data
UpdateProfileSer
class UpdateProfileSer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ("icon",)
I have a django model like this...
class ConversionResults(models.Model):
conversion_results_id = models.AutoField(primary_key=True)
conversion_rate_a = models.DecimalField(max_digits=4, decimal_places=2)
clicks_a = models.IntegerField()
conversion_rate_b = models.DecimalField(max_digits=4, decimal_places=2)
clicks_b = models.IntegerField()
week = models.IntegerField()
date = models.DateField()
time = models.TimeField()
objects = models.Manager()
class Meta:
db_table = 'conversion_results'
def __int__(self):
return self. conversion_results_id
When I try to add data to the model, like below
ConversionResults(
conversion_rate_a=conversion_rate_today_a,
conversion_rate_b=conversion_rate_today_b,
clicks_a=ctc_today_a,
clicks_b=ctc_today_b,
week=week,
date=today_date,
time=datetime.datetime.today().time() # the error is here
).save()
I am getting error with the time field as shown below
graphql.error.located_error.GraphQLLocatedError: [<class 'decimal.InvalidOperation'>]
I don't get how this is even related to decimal, the model contains a TimeField. Any help will be appreciated
Below is the full Traceback
Traceback (most recent call last):
File "/home/shashank/anaconda3/lib/python3.6/site-packages/promise/promise.py", line 487, in _resolve_from_executor
executor(resolve, reject)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/promise/promise.py", line 754, in executor
return resolve(f(*args, **kwargs))
File "/home/shashank/anaconda3/lib/python3.6/site-packages/graphql/execution/middleware.py", line 75, in make_it_promise
return next(*args, **kwargs)
File "/home/shashank/project/server/data_distribution/query.py", line 416, in resolve_daily_updates
time=datetime.datetime.today().time() # the error is here
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/base.py", line 779, in save_base
force_update, using, update_fields,
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/base.py", line 870, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _do_insert
using=using, raw=raw)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1331, in execute_sql
for sql, params in self.as_sql():
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1275, in as_sql
for obj in self.query.objs
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1275, in <listcomp>
for obj in self.query.objs
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1274, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1215, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1563, in get_db_prep_save
return connection.ops.adapt_decimalfield_value(self.to_python(value), self.max_digits, self.decimal_places)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/backends/base/operations.py", line 516, in adapt_decimalfield_value
return utils.format_number(value, max_digits, decimal_places)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 238, in format_number
value = value.quantize(decimal.Decimal(1).scaleb(-decimal_places), context=context)
graphql.error.located_error.GraphQLLocatedError: [<class 'decimal.InvalidOperation'>]
I am using Django to perform a very simple function. The application will grow in size as time goes on, but for now, all I want to do is run through an html document of all my Facebook messages, and save a model for every user, and every message attached to that user. However when trying to create an instance of a model I created, FacebookUser, I get the error "NoneType" object is not callable. I read other SO articles, and browsed the internet for other issues, and found that the error usually stemmed from trying to do something with the class itself, and not an instantiation of the class. However I am creating an instance of this class, and still getting this error.
models.py
from django.db import models
class FacebookUser(models.Model):
full_name = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return self.full_name
class Message(models.Model):
user = models.ForeignKey(FacebookUser)
content = models.TextField(max_length=10000, null=True, blank=True)
date_sent = models.DateTimeField(null=True, blank=True)
def __str__(self):
return '#{} {}'.format(self.id, self.user.full_name)
views.py
from django.http import HttpResponse
from facebook_user.models import FacebookUser, Message
from bs4 import BeautifulSoup
def crawl_messages(request):
data = open('messages.html', 'r').read()
soup = BeautifulSoup(data)
all_messages = soup.findAll("div", {"class": "message"})
msg_dictionaries = [{
'user': el.findAll('span')[0],
'time': el.findAll('span')[1],
'content': el.nextSibling.nextSibling
} for el in all_messages]
for msg in msg_dictionaries:
try:
fbuser = FacebookUser.objects.get(full_name=msg['user'])
print('Try One')
print(fbuser)
except FacebookUser.DoesNotExist:
fbuser = FacebookUser.objects.create(full_name=msg['user'])
print('Try Two')
print(fbuser)
except Exception as e:
print('Try Three')
print(e)
fbuser = None
if fbuser:
new_msg = Message()
new_msg.content = msg['content']
new_msg.user = fbuser
new_msg.save()
return HttpResponse('Worked ! Check the Admin')
Stack trace
Traceback (most recent call last):
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/timothybaney/Data Science/facebook_sentiment_analysis/facebook_user/views.py", line 19, in crawl_messages
fbuser = FacebookUser.objects.create(full_name=msg['user'])
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/query.py", line 401, in create
obj.save(force_insert=True, using=self.db)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/base.py", line 708, in save
force_update=force_update, update_fields=update_fields)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/base.py", line 736, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/base.py", line 820, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/base.py", line 859, in _do_insert
using=using, raw=raw)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/query.py", line 1039, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/sql/compiler.py", line 1059, in execute_sql
for sql, params in self.as_sql():
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/sql/compiler.py", line 1019, in as_sql
for obj in self.query.objs
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/sql/compiler.py", line 1019, in <listcomp>
for obj in self.query.objs
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/sql/compiler.py", line 1018, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/sql/compiler.py", line 946, in prepare_value
value = value.resolve_expression(self.query, allow_joins=False, for_save=True)
TypeError: 'NoneType' object is not callable
This most likely means that msg['user'] is not a string, but an object that sets any attribute when that attribute is called. And thus it receives resolve_expression attribute that causes above error.
For a fix, try casting msg['user'] to a string in your create statement:
fbuser = FacebookUser.objects.create(str(msg['user'])
This is just a guess, without full source to run it there's no way to be certain.