I am wondering if could anyone help out here, I am trying to send a post request to the URL, but I am not sure about the best way of doing it?
The idea here is to test the creation of the card object, but I am getting an error which I am not managing to figure out, if anyone could help me out here it would be fantastic.
here the code and the error below it
def test_create_card(self):
payload = {
'title': "Sample card title",
'description': 'Get a free coffee for every 10 coffee you buy',
'points_needed': 10,
}
res = self.client.post(CARDS_URL, self.company, **payload)
print(res)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
card = Card.objects.get(id=res.data['id'])
for k, v in payload.items():
self.assertEqual(getattr(card, k), v)
self.assertEqual(card.company, self.company)
ERROR
ERROR: test_create_card (card.tests.test_card_api.PrivateCardAPITests)
Test creating a card
Traceback (most recent call last):
File "/app/card/tests/test_card_api.py", line 141, in test_create_card
res = self.client.post(CARDS_URL, self.company, **payload)
File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 295, in post
response = super().post(
File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 208, in post
data, content_type = self._encode_data(data, format, content_type)
File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 179, in _encode_data
ret = renderer.render(data)
File "/py/lib/python3.9/site-packages/rest_framework/renderers.py", line 914, in render
return encode_multipart(self.BOUNDARY, data)
File "/py/lib/python3.9/site-packages/django/test/client.py", line 245, in encode_multipart
for (key, value) in data.items():
AttributeError: 'Company' object has no attribute 'items
'
and here is the model:
'
class Card(models.Model):
company = models.ForeignKey(Company, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, blank=True)
description = models.TextField(blank=True)
points_needed = models.IntegerField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True, blank=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.title
'
Related
I'm trying to serialize an object details which contains ForeignKey and OneToOneField.
Here is my Model:
user = models.OneToOneField(
"User",
on_delete=models.CASCADE,
null=False,
blank=False,
verbose_name="User",
help_text="The user who subscribed.",
related_name="subscription_information",
unique=True,
)
subscription = models.ForeignKey(
Subscription,
on_delete=models.CASCADE,
null=False,
blank=False,
related_name="subscription_information",
verbose_name="Subscription",
help_text="This is the subscription.",
)
subscription_type = models.IntegerField(
choices=SUBSCRIPTION_TYPES_CHOICES,
default=SubscriptionTypes.monthly,
null=False,
blank=False,
verbose_name="Subscription Type",
help_text="",
)
next_payment_amount = models.FloatField(
default=0.0,
null=False,
blank=True,
verbose_name="Subscription Plan Next Payment Amount",
help_text=(""),
)
next_payment_date = models.DateTimeField(
null=True,
blank=True,
default=None,
verbose_name="Next Payment Date",
help_text=(""),
)
payment_made = models.BooleanField(
null=False,
blank=True,
default=False,
verbose_name="Is Payment Made",
help_text=(
""
),
)
subscription_date = models.DateTimeField(
null=True,
blank=True,
default=None,
verbose_name="Subscription Date",
help_text="",
)
As you see User field is OneToOneField and Subscription field is foreign key.
And here is my serializer:
class SubscriptionInformationDetailSerializer(serializers.ModelSerializer):
class Meta:
model = SubscriptionInformation
fields = (
"id",
"user",
"subscription",
"subscription_type",
"next_payment_amount",
"next_payment_date",
"payment_made",
"subscription_date",
)
I want to return serialized SubscriptionInformation with this code:
subscription_information = SubscriptionInformation.objects.get(user_id=user.id)
serializer = SubscriptionInformationDetailSerializer(subscription_information, read_only=True)
return serializer
But it throws this error:
Traceback (most recent call last):
File "E:\Programming\project\venv\lib\site-packages\django\core\handlers\exception.py", line 42, in inner
response = get_response(request)
File "E:\Programming\project\venv\lib\site-packages\django\core\handlers\base.py", line 217, in _get_response
response = self.process_exception_by_middleware(e, request)
File "E:\Programming\project\venv\lib\site-packages\django\core\handlers\base.py", line 215, in _get_response
response = response.render()
File "E:\Programming\project\venv\lib\site-packages\django\template\response.py", line 109, in render
self.content = self.rendered_content
File "E:\Programming\project\venv\lib\site-packages\rest_framework\response.py", line 72, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "E:\Programming\project\venv\lib\site-packages\rest_framework\renderers.py", line 105, in render
allow_nan=not self.strict, separators=separators
File "E:\Programming\project\venv\lib\site-packages\rest_framework\utils\json.py", line 28, in dumps
return json.dumps(*args, **kwargs)
File "C:\Python27\Lib\json\__init__.py", line 251, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "C:\Python27\Lib\json\encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python27\Lib\json\encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "E:\Programming\project\venv\lib\site-packages\rest_framework\utils\encoders.py", line 68, in default
return super(JSONEncoder, self).default(obj)
File "C:\Python27\Lib\json\encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: DetailSerializer(<Thing: Thing object>, read_only=True):
id = IntegerField(label='ID', read_only=True)
user = PrimaryKeyRelatedField(help_text='The user who subscribed.', queryset=User.objects.all(), validators=[<UniqueValidator(queryset=SubscriptionInformation.objects.all())>])
subscription = PrimaryKeyRelatedField(help_text='This is the subscription.', queryset=Subscription.objects.all())
subscription_type = ChoiceField(choices=((0, 'Monthly'), (1, 'Annual')), help_text='', label='Subscription Type', required=False, validators=[<django.core.validators.MinValueValidator object>, <django.core.validators.MaxValueValidator object>])
next_payment_amount = FloatField(help_text='', label='Subscription Plan Next Payment Amount', required=False)
next_payment_date = DateTimeField(allow_null=True, help_text='', label='Next Payment Date', required=False)
payment_made = BooleanField(help_text='', label='Is Payment Made', required=False)
subscription_date = DateTimeField(allow_null=True, help_text='', label='Subscription Date', required=False) is not JSON serializable
I couldn't understand why can't I serialize this. Why it's not JSON serializable
Ok, No problem with model and serializer. I just need to return the serializer.data. So my code should be like that:
subscription_information = SubscriptionInformation.objects.get(user_id=user.id)
serializer = SubscriptionInformationDetailSerializer(subscription_information, read_only=True)
return serializer.data
Model File
class Report_item(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=255, help_text='*Title for the post e.g. item identity')
item_type = models.CharField(default="", max_length=100,
help_text='*Enter the item name you found e.g. Marksheet,key,wallet')
location = models.CharField(max_length=60, help_text='*Enter the address/street where you find this item')
city = models.CharField(max_length=60, help_text='*Enter the city name')
date = models.DateTimeField(default=timezone.now)
Description = models.TextField(help_text='*Enter full description about item')
publish = models.BooleanField(default=False)
image = models.FileField(default="add Item image",
help_text='*Please uplocad a item image to identify by the owner')
def __str__(self):
return self.title + " " + str(self.publish)
def get_absolute_url(self):
return reverse('feed:detail', kwargs={'pk': self.pk})
class Meta:
ordering = ["-date"]
I print my title in the shell.
>>> qs=Report_item.objects.filter(id=3)
>>> print(qs[0].title)
bunch of key with home keyring
But I got an error when I tried to print(qs[0].owner)
My foreign key is the Django auth user.
>>> print(qs[0].owner)
Traceback (most recent call last):
File "/home/imsaiful/Desktop/local_repo/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 178, in __get__
rel_obj = getattr(instance, self.cache_name)
AttributeError: 'Report_item' object has no attribute '_owner_cache'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/imsaiful/Desktop/local_repo/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 184, in __get__
rel_obj = self.get_object(instance)
File "/home/imsaiful/Desktop/local_repo/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 159, in get_object
return qs.get(self.field.get_reverse_related_filter(instance))
File "/home/imsaiful/Desktop/local_repo/myvenv/lib/python3.6/site-packages/django/db/models/query.py", line 379, in get
self.model._meta.object_name
django.contrib.auth.models.DoesNotExist: User matching query does not exist.
admin section image:
https://drive.google.com/file/d/1lQ-TcdaTCxj-cmnzfhlGZXql-KbWpIjW/view?usp=sharing
I'm a beginner trying to view a basic queryset with two records. I'm not able to process the request. Looking for some help.
class TestVenue(models.Model):
venue_name = models.CharField(max_length=40)
venue_city = models.CharField(max_length=20, null=True, blank=True)
venue_province = models.CharField(max_length=20, null=True, blank=True)
venue_shortcode = models.CharField(max_length=20, null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
update = models.DateTimeField(auto_now=True)
my_date_field = models.DateField(auto_now=False, auto_now_add=False)
def __str__(self):
return self.venue_name
my views.py is pretty simple
def venues_listview(request):
template_name = 'venues_list.html'
queryset = TestVenue.objects.all()
context = {
"object_list": queryset
}
return render(request, template_name, context)
from the shell i want to see my queryset but i get the following error:
>>> from venues.models import TestVenue
>>> TestVenue.object.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: type object 'TestVenue' has no attribute 'object'
>>> TestVenue.objects.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\users\frank\desktop\test_env\lib\site-packages\django\db\models\query.py", line 229, in __repr__
return '<%s %r>' % (self.__class__.__name__, data)
File "C:\users\frank\desktop\test_env\lib\site-packages\django\db\models\base.py", line 589, in __repr__
u = six.text_type(self)
File "C:\users\frank\desktop\test_env\src\venues\models.py", line 14, in __str__
# return self.venue_name
TypeError: decoding str is not supported
Your error is in this line,
TestVenue.object.all()
It should be,
TestVenue.objects.all()
objects is the attribute which calls the default manager, not object.
I rebooted my computer and it's now working. I had tried starting and stopping the server but that had not fixed the issue. Thanks for the help.
I was using Whoosh with Haystack and everything works fine, I want to change to ElasticSearch but when I run rebuild_index I get the following error. I am not sure why the error is happening, it appears to be complaining about my Models and the data, however if I switch back to Whoosh search/indexing all work fine.
Django==1.8.4
elasticsearch==2.3.0
django-haystack==2.4.1
File
"C:\Users\user.virtualenvs\pguider\lib\site-packages\elasticsearch\serializer.py",
line 50, in dumps
raise SerializationError(data, e) elasticsearch.exceptions.SerializationError: ({u'django_id': u'1',
'created': '2016-02-13T22:19:28.037000+00:00', 'suppl ier_code':
u'BL32291', 'related_supplier_parts': [], u'django_ct':
u'products.supplierpart', 'supplier': u'Parts Town', 'text':
u'BL32291\n32291\nBlodgett\n\nParts Town\n\n\n', 'part_code':
u'32291', u'id': u'products.supplierpart.1'}, Type Error("Unable to
serialize [] (type: )",))
Here are my models:
from django.db import models
class Supplier(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return u'%s' % self.name
class Part(models.Model):
name = models.CharField(max_length=200, null=True)
code = models.CharField(max_length=30, null=True)
def __unicode__(self):
return u'%s %s' % (self.code, self.name)
class SupplierPart(models.Model):
part = models.ForeignKey(Part)
supplier = models.ForeignKey(Supplier)
supplier_code = models.CharField(max_length=30)
description = models.CharField(max_length=200)
price = models.CharField(max_length=6, null=True)
sale_price = models.CharField(max_length=6, null=True)
quantity = models.IntegerField(null=True)
photo = models.ImageField(upload_to='products', null=True)
url = models.URLField()
created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.supplier_code
#property
def related_supplier_parts(self):
return self.part.supplierpart_set.all().exclude(pk=self.pk)
The problem lays in your property related_supplier_parts. Elastic search can't serialize it. This property returns queryset.
>>> parts = Part.objects.all()
>>> import json
>>> json.dumps({'related_supplier_parts': parts})
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.7/json/__init__.py", line 243, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: [] is not JSON serializable
How to solve it?
The best for any project is to not complicate your models with properties. Although we know they are widely used and easy to write. I have never used any property in my Django career. In my current project I have 153 models and not a single property. In 99% cases you don't need them because simple method get_related_supplier_parts should do same job.
class SupplierPart(models.Model):
[...]
created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.supplier_code
def get_related_supplier_parts(self):
return self.part.supplierpart_set.all().exclude(pk=self.pk)
One more downside of #property is whenever you try to serialize object additional queries will be executed and think about serializing millions of them. You don't need to worry about it with method.
If you reject this for some reason you will need to find a way to convert this query to list. Probably in your index class defining new field:
class MyIndex(indexes.SearchIndex, indexes.Indexable):
[...]
related_supplier_parts = indexes.MultiValueField()
def prepare_related_supplier_parts(self, obj):
return [part.id for part in obj.related_supplier_parts]
my old models.py :
from django.db import models
from taggit.managers import TaggableManager
from django.utils.encoding import smart_unicode
import markdown
class PublishedManager(models.Manager):
def get_query_set(self):
return super(PublishedManager, self).get_query_set().filter\
(is_published=True)
class Category(models.Model):
name = models.CharField(max_length=55)
def __unicode__(self):
return u"%s" %(self.name)
class BookMarks(models.Model):
name = models.CharField(max_length=255)
url = models.URLField()
date_time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return u"%s %s %s" %(self.name, self.url, self.date_time)
class Post(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
excerpt = models.TextField(blank=True, help_text="A small teaser of\
your content")
content = models.TextField(blank=True, null=True)
contentmarkdown = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
is_published = models.BooleanField(default=True)
objects = models.Manager()
published_objects = PublishedManager()
tags = TaggableManager()
category = models.ForeignKey(Category)
def save(self):
self.content = markdown.markdown(self.contentmarkdown)
super(Post, self).save() # Call the "real" save() method.
class Meta:
ordering = ("date_created",)
def __unicode__(self):
return smart_unicode("%s %s %s %s %s" %(self.title, self.content, self.is_published, self.category, self.tags))
def get_absolute_url(self):
return "/posts/%s/" % self.id
class Book(models.Model):
name = models.CharField(max_length=55)
author = models.CharField(max_length=55)
image = models.ImageField(upload_to="static/img/books/")
body = models.TextField(blank=True, null=True)
bodymarkdown = models.TextField()
def __unicode__(self):
return u"%s %s" %(self.name, self.author)
def get_absolute_url(self):
return "/books/%s/" % self
.id
and after add "category = models.ForeignKey(Category)" this field to Book and BookMarks table, my new models.py like this:
from django.db import models
from taggit.managers import TaggableManager
from django.utils.encoding import smart_unicode
import markdown
class PublishedManager(models.Manager):
def get_query_set(self):
return super(PublishedManager, self).get_query_set().filter\
(is_published=True)
class Category(models.Model):
name = models.CharField(max_length=55)
def __unicode__(self):
return u"%s" %(self.name)
class BookMarks(models.Model):
name = models.CharField(max_length=255)
url = models.URLField()
date_time = models.DateTimeField(auto_now_add=True)
category = models.ForeignKey(Category)
def __unicode__(self):
return u"%s %s %s" %(self.name, self.url, self.date_time)
class Post(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
excerpt = models.TextField(blank=True, help_text="A small teaser of\
your content")
content = models.TextField(blank=True, null=True)
contentmarkdown = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
is_published = models.BooleanField(default=True)
objects = models.Manager()
published_objects = PublishedManager()
tags = TaggableManager()
category = models.ForeignKey(Category)
def save(self):
self.content = markdown.markdown(self.contentmarkdown)
super(Post, self).save() # Call the "real" save() method.
class Meta:
ordering = ("date_created",)
def __unicode__(self):
return smart_unicode("%s %s %s %s %s" %(self.title, self.content, self.is_published, self.category, self.tags))
def get_absolute_url(self):
return "/posts/%s/" % self.id
class Book(models.Model):
name = models.CharField(max_length=55)
author = models.CharField(max_length=55)
image = models.ImageField(upload_to="static/img/books/")
body = models.TextField(blank=True, null=True)
bodymarkdown = models.TextField()
category = models.ForeignKey(Category)
def __unicode__(self):
return u"%s %s" %(self.name, self.author)
def get_absolute_url(self):
return "/books/%s/" % self.id
class Errors(models.Model):
name = models.CharField(max_length=255)
created = models.DateTimeField(auto_now_add=True)
body = models.TextField(blank=True, null=True)
bodymarkdown = models.TextField()
def __unicode__(self):
return self.name
def get_absolute_url(self):
return "/errors/%s/" % self.id
I used south. Everything was going OK but after this line:
? 1. Quit now, and add a default to the field in models.py
? 2. Specify a one-off value to use for existing columns now
? 3. Disable the backwards migration by raising an exception.
? Please select a choice: 2
? Please enter Python code for your one-off default value.
? The datetime module is available, so you can do e.g. datetime.date.today()
>>> datetime.datetime.now()
I get an error like this:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/management/commands/migrate.py", line 108, in handle
ignore_ghosts = ignore_ghosts,
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/__init__.py", line 213, in migrate_app
success = migrator.migrate_many(target, workplan, database)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 235, in migrate_many
result = migrator.__class__.migrate_many(migrator, target, migrations, database)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 310, in migrate_many
result = self.migrate(migration, database)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 133, in migrate
result = self.run(migration)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 106, in run
dry_run.run_migration(migration)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 191, in run_migration
self._run_migration(migration)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 178, in _run_migration
raise exceptions.FailedDryRun(migration, sys.exc_info())
south.exceptions.FailedDryRun: ! Error found during dry run of '0012_auto__del_field_book_category__add_field_book_category1__del_field_boo'! Aborting.
Traceback (most recent call last):
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 175, in _run_migration
migration_function()
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 57, in <lambda>
return (lambda: direction(orm))
File "/home/ada/mainproject/blog/migrations/0012_auto__del_field_book_category__add_field_book_category1__del_field_boo.py", line 17, in forwards
keep_default=False)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/db/generic.py", line 44, in _cache_clear
return func(self, table, *args, **opts)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/db/generic.py", line 402, in add_column
sql = self.column_sql(table_name, name, field)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/db/generic.py", line 688, in column_sql
default = field.get_db_prep_save(default, connection=self._get_connection())
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 991, in get_db_prep_save
connection=connection)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 292, in get_db_prep_save
prepared=False)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 284, in get_db_prep_value
value = self.get_prep_value(value)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 537, in get_prep_value
return int(value)
TypeError: int() argument must be a string or a number, not 'datetime.datetime'
Please can you tell me Why I get this error? What must I do?
Because your new category field is mandatory (you can't create a book or bookmark without giving it a category), south asked you what to do with the existing books and bookmarks in your database - your latest changes would have made all your current books / bookmarks invalid (since they don't have a category).
Your new category field is represented in your book/bookmark tables using a primary key of the category table. This primary key will likely be an integer (or possibly a string).
South asked you to supply a default primary key. Instead of supplying the primary key of an category object in your database (which would be an integer or a string). You've supplied a datatime object.
It's crapping out when it actually runs the migration because the field doesn't hold datetime objects. It holds integers (or strings). you need to create the migration again and add a valid primary key.