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'>]
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)
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()
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.
I have a django app which is running on 1.6 with python 3. Recently I have added django-storages to my app.
When I am trying to save a model(record) which worked well previously, its showing up the below error
Traceback (most recent call last):
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/core/handlers/base.py", line 112, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/contrib/admin/options.py", line 432, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/utils/decorators.py", line 99, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/views/decorators/cache.py", line 52, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/contrib/admin/sites.py", line 198, in inner
return view(request, *args, **kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/utils/decorators.py", line 29, in _wrapper
return bound_func(*args, **kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/utils/decorators.py", line 99, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/utils/decorators.py", line 25, in bound_func
return func(self, *args2, **kwargs2)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/transaction.py", line 371, in inner
return func(*args, **kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/contrib/admin/options.py", line 1131, in add_view
self.save_model(request, new_object, form, False)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/contrib/admin/options.py", line 860, in save_model
obj.save()
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/base.py", line 545, in save
force_update=force_update, update_fields=update_fields)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/base.py", line 573, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/base.py", line 654, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/base.py", line 687, in _do_insert
using=using, raw=raw)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/manager.py", line 232, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/query.py", line 1514, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 902, in execute_sql
for sql, params in self.as_sql():
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 860, in as_sql
for obj in self.query.objs
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 860, in <listcomp>
for obj in self.query.objs
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 858, in <listcomp>
for f in fields
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/fields/files.py", line 252, in pre_save
file.save(file.name, file, save=False)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/fields/files.py", line 87, in save
setattr(self.instance, self.field.name, self.name)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/fields/files.py", line 311, in __set__
self.field.update_dimension_fields(instance, force=True)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/fields/files.py", line 381, in update_dimension_fields
width = file.width
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/core/files/images.py", line 17, in _get_width
return self._get_image_dimensions()[0]
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/core/files/images.py", line 27, in _get_image_dimensions
self.open()
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/db/models/fields/files.py", line 76, in open
self.file.open(mode)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/core/files/base.py", line 121, in open
if not self.closed:
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/django/core/files/base.py", line 59, in _get_closed
return not self.file or self.file.closed
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/storages/backends/s3boto.py", line 406, in _get_file
self.key.get_contents_to_file(self._file)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/boto/s3/key.py", line 1643, in get_contents_to_file
response_headers=response_headers)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/boto/s3/key.py", line 1475, in get_file
query_args=None)
File "/Users/david/.virtualenvs/project/lib/python3.4/site-packages/boto/s3/key.py", line 1529, in _get_file_internal
fp.write(bytes)
TypeError: string argument expected, got 'bytes'
model
class RequisitionImage(models.Model, ImageRisizeToolbox):
image_id = models.AutoField(primary_key=True)
requisition = models.ForeignKey(Requisition)
description = models.CharField(max_length=80)
image_file = models.ImageField(upload_to=get_file_path, height_field='image_height', width_field='image_width')
thumbnail_file = models.ImageField(upload_to=get_file_path, blank=True, null=True)
sort_order = models.SmallIntegerField(blank=True, null=True)
filetype = models.CharField(max_length=10, blank=True, null=True)
objects = models.Manager()
cust_objects = RequisitionImageManager()
MAX_SIZE = 4000000 # Image file size limit
def __str__(self):
return self.description
I am getting this error when i am trying to save the RequisitionImage object record both from the admin model and from my view.
So how to avoid this error and what is causing it ?