I'm following a Django book (Django 1.0 Web Site Development). I'm finding that the book, although straight forward and easy to read, leaves out small details. However, this error that I'm getting, I have not been able to find a solution online. Thanks for any help.
Below, I added the Tag class to my models.py file.
from django.db import models
from django.contrib.auth.models import User
class Link(models.Model):
url = models.URLField(unique=True)
class Bookmark(models.Model):
title = models.CharField(max_length=200)
user = models.ForeignKey(User)
link = models.ForeignKey(Link)
class Tag(models.Model):
name = models.CharField(max_length=64, unique=True)
bookmarks = models.ManyToManyField(Bookmark)
Then I attempt to run the following code at the python shell:
from bookmarks.models.import *
bookmark = Bookmark.objects.get(id=1)
As a result, I get the following error:
Traceback (most recent call last):
File "(console)", line 1, in (module)
File "c:\Python27\lib\site\-packages\django\db\models\manager.py", line 132, in get
return self.get_query_set().get(*args, **kwargs)
File "c:\Python27\lib\site-packages\django\db\models\query.py", line 349, in get
% self.model._meta.object_name)
DoesNotExist: Bookmark matching query does not exist.
The error means just what it says. DoesNotExist is raised by QuerySet.get() if there is no object in the database that would match the conditions given to the QuerySet. In this case it means there is no Bookmark object in the database with an ID equal to 1.
Did you add any data in the Bookmark table yet? DoesNotExist is raised by get if there is no record corresponding to your query. i.e. if there is no record corresponding to id=1.
Related
I am trying to use 'natural keys' for serialization (docs) in a "manage.py dumpdata" command:
python manage.py dumpdata --natural-primary --natural-foreign --indent 4 --format json --verbosity 1 > tests\test_fixtures\test_db2.json
and I am getting the following error when I use --natural-foreign on other apps that use the Project or Task model (which they all must by design):
CommandError: Unable to serialize database: Object of type Project is not JSON serializable
Exception ignored in: <generator object cursor_iter at 0x000001EF62481B48>
Traceback (most recent call last):
File "C:\Users\Andrew\anaconda3\envs\Acejet_development\lib\site-packages\django\db\models\sql\compiler.py", line 1586, in cursor_iter
cursor.close()
sqlite3.ProgrammingError: Cannot operate on a closed database.
If I just dumpdata from this, the 'projects' app, it works, but other apps are built with entities related to Project or Task and there the --natural-foreign option fails.
The problem occurs when a model (say Question) calls for a natural_key from Task, which includes a for a natural_key from Project.
If I use the Pycharm Python Console to access querysets of Projects or Tasks ('q' here), this works:
serializers.serialize('json', q, indent=2, use_natural_foreign_keys=True, use_natural_primary_keys=True)
But if 'w' is a list of Question objects from another app that have a Task foreign key I get this error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Users\Andrew\anaconda3\envs\Acejet_development\lib\site-packages\django\core\serializers\__init__.py", line 128, in serialize
s.serialize(queryset, **options)
File "C:\Users\Andrew\anaconda3\envs\Acejet_development\lib\site-packages\django\core\serializers\base.py", line 115, in serialize
self.end_object(obj)
File "C:\Users\Andrew\anaconda3\envs\Acejet_development\lib\site-packages\django\core\serializers\json.py", line 53, in end_object
json.dump(self.get_dump_object(obj), self.stream, **self.json_kwargs)
File "C:\Users\Andrew\anaconda3\envs\Acejet_development\lib\json\__init__.py", line 179, in dump
for chunk in iterable:
File "C:\Users\Andrew\anaconda3\envs\Acejet_development\lib\json\encoder.py", line 431, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "C:\Users\Andrew\anaconda3\envs\Acejet_development\lib\json\encoder.py", line 405, in _iterencode_dict
yield from chunks
File "C:\Users\Andrew\anaconda3\envs\Acejet_development\lib\json\encoder.py", line 405, in _iterencode_dict
yield from chunks
File "C:\Users\Andrew\anaconda3\envs\Acejet_development\lib\json\encoder.py", line 325, in _iterencode_list
yield from chunks
File "C:\Users\Andrew\anaconda3\envs\Acejet_development\lib\json\encoder.py", line 438, in _iterencode
o = _default(o)
File "C:\Users\Andrew\anaconda3\envs\Acejet_development\lib\site-packages\django\core\serializers\json.py", line 104, in default
return super().default(o)
File "C:\Users\Andrew\anaconda3\envs\Acejet_development\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Project is not JSON serializable
The models are:
# projects.models.py
class BaseModelWithHistory(models.Model):
history = HistoricalRecords(inherit=True)
natural_key_fields = ('id',) # default
class Meta:
abstract = True
def natural_key(self):
fieldlist = [getattr(self, fieldname) for fieldname in self.natural_key_fields]
return tuple(fieldlist)
# natural_key.dependencies = ['projects.Project', 'projects.Task'] # serialize these first.
class Project(BaseModelWithHistory):
"""
'Projects' group Tasks.
"""
project_name = models.CharField(max_length=200, default="development_project")
project_short_description = models.CharField(
max_length=500,
default="This is the default text.")
target_group = models.ManyToManyField(Group, blank=True)
objects = ProjectDiscreteManager()
natural_key_fields = ('project_name',)
class Task(BaseModelWithHistory):
number = models.PositiveIntegerField(default=0)
name = models.CharField(max_length=200, default='new task')
project = models.ForeignKey(Project, on_delete=models.CASCADE)
target_group = models.ManyToManyField(Group, blank=True)
app_label = models.CharField(max_length=80, choices=app_choices(), null=True, blank=True)
objects = discrete_manager_factory('project')
natural_key_fields = ('project', 'name', 'number')
Things that I wouldn't expect to cause this problem but I could certainly be wrong:
The ProjectDiscreteManager and others created by discrete_manager_factory() behave exactly as the default manager (models.Manager()), unless its called with a request from an identified user, in which case it adds a filter to see if that user is in the Group.
All models define the natural_keys tuple because the parent class defines it as ('id',); most models overwrite this with more representative fields.
With the natural_key.dependencies list set for all models to prioritize Project and then Task, I get a 'can't resolve dependencies' error for every other model. I think this ticket relates, but am not sure how to track down whether this fix is already in the Django 3.0.6 I'm using and I should just straighten up & fly right, or if my Han Solo 'this should wooork' will one day soon be rewarded. [Update: I worked out it is coming in Django 3.1.1, but I'm not sure that it is going to fix the "can't resolve dependencies" error I've created for myself.]
I have searched and tried out all solutions provided for this question in similar problem but they're not working for me. I am getting the following error when trying to get data from an endpoint
Got AttributeError when attempting to get a value for field
hotel_type on serializer HotelDetailSerializer. The serializer
field might be named incorrectly and not match any attribute or key on
the Hotels instance. Original exception text was: 'Hotels' object
has no attribute 'get_hotel_Type_display'.
This is my model field truncated for clarity
class Hotels(models.Model):
HOTEL_TYPE = (
('hotel', "Hotel"),
('apartment', "Apartment"),
('villa', "Villa"),
hotel_Type = models.CharField(
max_length=20,
choices=HOTEL_TYPE,
default='hotel', null=True, blank=True
#property
def hotel_type(self):
return self.get_hotel_Type_display()
This is my serializer class also truncated for clarity
class HotelDetailSerializer(serializers.ModelSerializer):
hotel_type = serializers.Field(source='hotel_type.hotel_Type')
class Meta:
model = Hotels
fields = ("hotel_type" )
This is the apiview
class HotelDetailAPIView(RetrieveAPIView):
"""Display details of a single hotel"""
queryset = Hotels.objects.all()
serializer_class = HotelDetailSerializer
permission_classes = ()
lookup_field = 'slug'
Could anyone kindly assist me figure out why this is not working? Thanks
EDIT
I am editing this question to add more context. I have been doing some debugging in Django shell. This is what i am getting
>>> from hotels.models import Hotels
>>> h = Hotels.objects.all()
>>> for n in h:
... print (n.hotel_Type)
...
(<django.db.models.fields.CharField>,)
>>> for n in h:
... print (n.get_hotel_Type_display())
...
Traceback (most recent call last):
File "<console>", line 2, in <module>
AttributeError: 'Hotels' object has no attribute 'get_hotel_Type_display'
I am following Django's get_FOO_display() tutorial and i still cannot get this work. I am not seeing anything wrong with my Hotels model. Could this be a bug in Django? Kindly assist
This really has eaten me up. I finally found the issue was a misplaced comma on my model field as shown below
class Hotels(models.Model):
HOTEL_TYPE = (
('hotel', "Hotel"),
('apartment', "Apartment"),
('villa', "Villa"),
hotel_Type = models.CharField(
max_length=20,
choices=HOTEL_TYPE,
default='hotel', null=True, blank=True
),# <--------------This comma was the source of my problems
#property
def hotel_type(self):
return self.get_hotel_Type_display()
I`m having a hard time migrating my models from standard Django orm with MySQL to mongoengine-odm.
I have the following model that works fine in the old structure:
class Place(Document):
name = StringField()
acronym = StringField()
parent = ReferenceField('self')
hierarchy = ListField(ReferenceField('self'))
hierarchy_size = IntField()
#classmethod
def preSave(instance, sender, **kwargs):
instance.hierarchy_size = len(instance.hierarchy)
signals.pre_save.connect(Place.preSave, sender=Place)
But when working with the new mongoengine, I'm facing problems to access the objects hierarchy size in the way I was doing before. Receiving:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/awesome_user/workspace/awesome_project/project/models.py", line 728, in importPlacesFromMySQL
myCountry.save()
File "/Users/awesome_user/workspace/awesome_project/site_env/lib/python2.7/site-packages/mongoengine/document.py", line 220, in save
signals.pre_save.send(self.__class__, document=self)
File "/Users/awesome_user/workspace/awesome_project/site_env/lib/python2.7/site-packages/blinker/base.py", line 267, in send
for receiver in self.receivers_for(sender)]
File "/Users/awesome_user/workspace/awesome_project/project/models.py", line 804, in preSave
instance.hierarchy_size = len(instance.hierarchy)
TypeError: object of type 'ListField' has no len()
Does anyone know how to access the properties of the instance, like the length in my case?
You have a mistake in defining preSave classmethod. You are trying to take a len from hierarchy ListField from Place class (not instance). This is because you are using the first argument of the method - it's not an instance, it's a class itself. Use the 3rd argument instead:
#classmethod
def preSave(cls, sender, document, **kwargs):
document.hierarchy_size = len(document.hierarchy)
len(object.field) will retrieve all child documents and then count. If you only want the length of the array without retrieving all the documents you can use len(object.to_mongo()["field"])
I want create a table with two primary_key by it's django model as below:
class UserView(Model):
email= columns.Text(primary_key=True)
entryLink= columns.Text(primary_key=True)
date= columns.Date(default=datetime.date.today())
but when I want create table as below:
>>> from cqlengine import connection
>>> from cqlengine.management import create_table
>>> from MainAPP.models import UserView
>>> connection.setup(['127.0.0.1:9160'])
>>> create_table(UserView)
I see this error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "H:\Web-Programming\Python\Project\Prexter\Virtual-Environment\Lib\site-packages\cqlengine\management.py", line 97, in create_table
execute(qs)
File "H:\Web-Programming\Python\Project\Prexter\Virtual-Environment\Lib\site-packages\cqlengine\connection.py", line 172, in execute
return connection_pool.execute(query, params)
File "H:\Web-Programming\Python\Project\Prexter\Virtual-Environment\Lib\site-packages\cqlengine\connection.py", line 164, in execute
raise CQLEngineException(unicode(ex))
CQLEngineException: Bad Request: Missing CLUSTERING ORDER for column entryLink
When I remove primary_key property from entryLink field, I have no error! but I want define entryLink as a primary_key! What is my mistake?
A database table cannot have 2 primary key. If you are looking for a Composite Primary Key, Django does not support that yet.
Now, what you might be looking for is unique=True (a candidate key).
class UserView(Model):
email= columns.Text(primary_key=True)
entryLink= columns.Text(unique=True)
date= columns.Date(default=datetime.date.today())
You can also read this post for a better understanding
I found My Answer! This is a funny bug!
I have a capitalized character among entryLink field, and it caused considered error! This is so funny! because this applies to primary_key only! and it isn't true about other fields!!! primary_keys can't have a capitalized character among!
My modified code:
class UserView(Model):
email= columns.Text(primary_key=True)
link= columns.Text(primary_key = True)
date= columns.Date(default=datetime.date.today())
I have recently started django-tastypie and so far loving the framework. With said that, I am getting below issue on POST for OneToOne relation to model and spent good amount of time but couldn't figured whats missing. Here is the Model and Resource code -
Model
class Question(TimeStampedModel):
question_title = models.CharField("question title", max_length=100)
question_desc = models.TextField("question description", max_length=1000)
.......
Second model is having OneToOne relation with Question -
class QuestionAnswer(TimeStampedModel):
question = models.OneToOneField(Question)
.....
Resource
QuestionAnswerResource -
class QuestionAnswerResource(ModelResource):
question = fields.ForeignKey('myapp.api.QuestionResource', 'question')
class Meta:
queryset = QuestionAnswer.objects.all()
resource_name='questionanswer'
QuestionResource -
class QuestionResource(ModelResource):
questionanswer = fields.OneToOneField('myapp.api.QuestionAnswerResource', 'questionanswer', full=True)
class Meta:
queryset = Question.objects.all()
resource_name = 'question'
With the above setup, I get correct response on GET with Question instance along with its answer attribute. However when I try to POST data to save question/answer on this one it fails with below error -
"{"error_message": "", "traceback": "Traceback (most recent call
last):\n\n File
\"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 192,
...................................................................................... line 636, in hydrate\n
value = super(ToOneField, self).hydrate(bundle)\n\n File
\"/Library/Python/2.7/site-packages/tastypie/fields.py\", line 154, in
hydrate\n elif self.attribute and getattr(bundle.obj,
self.attribute, None):\n\n File
\"/Library/Python/2.7/site-packages/Django-1.4.1-py2.7.egg/django/db/models/fields/related.py\", line 343, in get\n raise
self.field.rel.to.DoesNotExist\n\nDoesNotExist\n"}"
Can someone point out what I am missing?
I think that this:
questionanswer = fields.OneToOneField('myapp.api.QuestionAnswerResource', 'questionanswer', full=True)
causes problem. There is no questionanswer field in your Question model and Django expects that.
To test, you may want to see whether you can create instances in the shell. Tastypie docs say the following about the ToOneField:
This subclass requires Django’s ORM layer to work properly.
and I think this might not be the case here.
To provide answers for a question you may want to set related_name, like so:
question = fields.ForeignKey('myapp.api.QuestionResource', 'question', related_name = 'questionanswer')