InheritanceManager bug when access parent-class elements (Django 2.0) - django

I'm currently trying to have a object oriented schema in Django 2.0 (Python 3.6.3) with a parent class Program and some children classes Snippet and Software. I saw that the model_utils module contains some tools to handle the polymorphism, and tried to replicate the tutorial (http://django-model-utils.readthedocs.io/en/latest/managers.html), here is what it gives in my case:
models.py
from django.db import models
from model_utils.managers import InheritanceManager
class Program(models.Model):
name = models.CharField(max_length=100)
objects = InheritanceManager()
class Snippet(Program):
code = models.TextField()
class Software(Program):
repoLink = models.URLField()
Django shell
>>> from coding.models import Program
>>> programs = Program.objects.select_subclasses()
>>> programs
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "...\py3django\lib\site-packages\django\db\models\query.py", line 248, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "...\py3django\lib\site-packages\django\db\models\query.py", line 292, in __getitem__
qs = self._chain()
File "...\py3django\lib\site-packages\django\db\models\query.py", line 1156, in _chain
obj = self._clone()
File "...\py3django\lib\site-packages\model_utils\managers.py", line 100, in _clone
return super(InheritanceQuerySetMixin, self)._clone(**kwargs)
TypeError: _clone() got an unexpected keyword argument 'subclasses'
I don't understand this error and how to fix it, and even don't know if it is a fail in my design or a bad use of the InheritanceManager. So what can be the origin of this error message?

According to the docs, django-model-utils only supports Django 1.8 to 1.10.

Related

Got EOFError during loading doc2vec model

I could not load a doc2vec model on my computer and I got the following error. But, when I load that model on other computers, I can use that model.Therefore, I know the model was built correctly.
what should I do.
This is the code:
# coding: utf-8
from gensim.models.doc2vec import Doc2Vec
import gensim.models.doc2vec
from gensim.models.doc2vec import LabeledSentence
import os
import pickle
pth='/home/fatemeh/Step2/input-output/model/iterator'
model= Doc2Vec.load(pth+'/my_model.doc2vec')
This is the error:
Traceback (most recent call last):
File "CreateAnnoyIndex.py", line 16, in <module>
model= Doc2Vec.load(pth+'/my_model.doc2vec')
File "/usr/local/lib/python2.7/dist-packages/gensim-0.13.3-py2.7-linux-x86_64.egg/gensim/models/word2vec.py", line 1762, in load
model = super(Word2Vec, cls).load(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/gensim-0.13.3-py2.7-linux-x86_64.egg/gensim/utils.py", line 248, in load
obj = unpickle(fname)
File "/usr/local/lib/python2.7/dist-packages/gensim-0.13.3-py2.7-linux-x86_64.egg/gensim/utils.py", line 912, in unpickle
return _pickle.loads(f.read())
EOFError
I think your model causes the problem. Are you check with same model? I mean build in a same way. please see this page

Exception with Django 1.6.5 and factory_boy

I decided to use factory_boy in my simple django application for test purposes.
But I had a problem with simple example. Here is the code of my simple test.
from django.utils import unittest
from ..models import Server, ServerAddress, L2TPServer, serialize_open_vpn_server_json
from factory import django as django_factory
class SshOpenVpnServerFactory(django_factory.DjangoModelFactory):
class Meta:
model = L2TPServer
django_get_or_create = ('name', 'address')
name = 'Hello'
address = 'Nono'
class ServersTestCase(unittest.TestCase):
def test_serialize_server_info(self):
print Server.objects.all()
SshOpenVpnServerFactory.build()
When test-runner executes this test, I get an error:
Traceback (most recent call last):
File "/Users/green/Development/Wasel/experimental/wasel_services/packages/waselcore/backend/tests/test_models.py", line 20, in test_serialize_server_info
SshOpenVpnServerFactory.build()
File "/Users/green/Development/Wasel/experimental/env/wasel_sevices/lib/python2.7/site-packages/factory/base.py", line 504, in build
attrs = cls.attributes(create=False, extra=kwargs)
File "/Users/green/Development/Wasel/experimental/env/wasel_sevices/lib/python2.7/site-packages/factory/base.py", line 365, in attributes
force_sequence=force_sequence,
File "/Users/green/Development/Wasel/experimental/env/wasel_sevices/lib/python2.7/site-packages/factory/containers.py", line 265, in build
sequence = self.factory._generate_next_sequence()
File "/Users/green/Development/Wasel/experimental/env/wasel_sevices/lib/python2.7/site-packages/factory/base.py", line 338, in _generate_next_sequence
cls._setup_counter()
File "/Users/green/Development/Wasel/experimental/env/wasel_sevices/lib/python2.7/site-packages/factory/base.py", line 318, in _setup_counter
first_seq = cls._setup_next_sequence()
File "/Users/green/Development/Wasel/experimental/env/wasel_sevices/lib/python2.7/site-packages/factory/django.py", line 83, in _setup_next_sequence
manager = cls._get_manager(model)
File "/Users/green/Development/Wasel/experimental/env/wasel_sevices/lib/python2.7/site-packages/factory/django.py", line 76, in _get_manager
return target_class.objects
AttributeError: 'NoneType' object has no attribute 'objects'
Where am I wrong? Does factory_boy support django 1.6.5?
The proposed syntax using the Meta class will only be released as part of the (unreleased) Factory Boy 2.4. Use SshOpenVpnServerFactory.FACTORY_FOR instead. Related issue: https://github.com/rbarrois/factory_boy/issues/143

Attribute error while implementing filter in django manager

I have a manager in my django project and am implementing a filter as below.
I start the django shell and get this error:
>>> from django.http import HttpRequest
>>> r=HttpRequest()
>>> r.session=()
>>> from movierating.models import *
>>> RatingModel.statManager.RatingTimeLine(r)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/data/dashapp/movierating/managers.py", line 27, in RatingTimeLine
(data,display,err)=self.getdatacache(request)
File "/data/dashapp/movierating/managers.py", line 11, in getdatacache
filterDict=request.session.get('RatingFilter',{})
AttributeError: 'tuple' object has no attribute 'get'
>>> from django.http import HttpRequest
>>> r=HttpRequest()
>>> r.session()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'HttpRequest' object has no attribute 'session'r code here
The file manager.py looks like this:
import json,datetime
from django.db import models
from django.db.models import *
from pandas import *
from urllib import urlencode
import hashlib
from django.core.cache import cache
from web.extras import *
class RatingManager(models.Manager):
def getdatacache(self,request):
filterDict=request.session.get('RatingFilter',{})
(fapply,display,err)=normalizeFilter(self.model,filterDict)
cache_id=urlencode(fapply.items())
cache_id=hashlib.md5('RatingFilter'+cache_id).hexdigest()
data=None
if data==None:
res=self.model.objects.order_by('date').filter(**fapply).values('date').annotate(
RatingCounts = Count('rating'),
RatingSum = Sum('rating'),
)
data=DataFrame(list(res))
data['AverageRating']=data['RatingSum']/data['RatingCounts']
cache.set(cache_id,data)
return (data,display,err)
def RatingTimeLine(self,request):
jsondata={}
jsondata['chartconfig']={}
jsondata['chartconfig']['title']="Average Movie Rating per Day"
jsondata['chartconfig']['names']=['AverageRating']
(data,display,err)=self.getdatacache(request)
jsondata['chartconfig']['errors']="<br/>".join(err)
jsondata['chartconfig']['subtitle']="<br/>".join(display)
jsondata['series']=data[['data','AverageRating']].values.tolist()
data=json.dumps(jsondata,cls = SeriesEncoder)
return {'data':data}
I have this model in my models.py:
class RatingModel(models.Model):
movie=models.ForeignKey(MovieModel)
user=models.ForeignKey(userModel)
rating=models.IntegerField()
date=models.DateField()
objects=models.Manager() #default manager
statManager=RatingManager() #new manager class
# FilterMapping={
#'movie':'movie__name', #django relational
# }
def __unicode__(self):
return "id: %d rating for movie is %s" %(self.id,self.movie.name) #relationships
class Meta:
app_label = 'movierating'
db_table = 'rating'
What could be the possible error in this line?
filterDict=request.session.get('RatingFilter',{})
In your third line you say r.session=() - that is, you're assigning an empty tuple to r.session. Your code later tries to call get() on this tuple, which isn't a supported operation.
I'm not sure what you're trying to do here. request.session is normally filled in by the session middleware. If you're trying to test your code programmatically, you might want to look into the Django testing framework, which supports sessions.

Django Official Tutorial Part 1 index out of bound error

I started learning Django recently and am having a strange problem with the tutorial. Everything was going fine until I started playing with the interactive shell and then I got an error whenever I tried to call all the objects in one of the tables.
I am using Django 1.1, Python 2.5 on MacOs X.
For those unfamiliar with the tutorial you are making a website to manage Polls. You have the following code in the model:
from django.db import models
import datetime
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
was_published_today.short_description = 'Published today?'
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.choice
After creating the model you add a poll item and then add some choices to it.
Everything was fine until I tried to see all the objects in the choices table or tried to see all the choices in a particular poll. Then I got an error. Heres an example series of commands in the interactive shell. Please note that the count of the choices is correct (I have experimented a bit after running into the error so the count is a bit high.)
>>> from mysite.polls.models import Poll, Choice
>>> Poll.objects.all()
[<Poll: What's up>, <Poll: Yups>]
>>> Choice.objects.count()
10
>>> Choice.objects.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Python/2.5/site-packages/django/db/models/query.py", line 68, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/Library/Python/2.5/site-packages/django/db/models/query.py", line 83, in __len__
self._result_cache.extend(list(self._iter))
File "/Library/Python/2.5/site-packages/django/db/models/query.py", line 238, in iterator
for row in self.query.results_iter():
File "/Library/Python/2.5/site-packages/django/db/models/sql/query.py", line 287, in results_iter
for rows in self.execute_sql(MULTI):
File "/Library/Python/2.5/site-packages/django/db/models/sql/query.py", line 2369, in execute_sql
cursor.execute(sql, params)
File "/Library/Python/2.5/site-packages/django/db/backends/util.py", line 19, in execute
return self.cursor.execute(sql, params)
File "/Library/Python/2.5/site-packages/django/db/backends/sqlite3/base.py", line 193, in execute
return Database.Cursor.execute(self, query, params)
File "/Library/Python/2.5/site-packages/django/db/backends/util.py", line 82, in typecast_timestamp
seconds = times[2]
IndexError: list index out of range
The Django tutorial(part 1) can be found here
Thanks!
The problem seemed to be that the database was not synchronized with the models. Resetting the database worked fine. Thanks to Alasdair for the suggestion.
It looks like the problem is that was_published_today() is comparing a datetime to a date. Try changing it to:
return self.pub_date.date() == datetime.date.today()
Since the problem seems to be in the code that interprets strings as timestamps, I'd be interested to see the actual data in the db. It looks like there's a timestamp in there that isn't in the proper form. Not sure how it got there without seeing it, but I bet there's a clue there.

Django unittests: The model is already registered Error

I come across several problems while trying django unittests library. Something strange happens:
I defined the test like this:
from django.core import management
from django.test import TestCase
from django.test.client import Client
from django.core import mail
from django.test.utils import setup_test_environment
from django.contrib.auth.models import User
from django.db import connection
from goserver.models import ActiveList
class GoserverTestCase(TestCase):
#fixtures = ['dat.json']
def setUp(self):
pass
def test_active_list_works(self):
c = Client()
response = c.post('/')
#print response.status_code
self.assertEquals(True, True)
But after the execution of the code it returns following error:
---------------------------------------------------------------------- Unit Test Code Coverage Results
---------------------------------------------------------------------- Traceback (most recent call last): File "manage.py", line 11, in <module>
execute_manager(settings) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/__init__.py", line 340, in execute_manager
utility.execute() File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/__init__.py", line 295, in execute
self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/base.py", line 192, in run_from_argv
self.execute(*args, **options.__dict__) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/base.py", line 219, in execute
output = self.handle(*args, **options) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/core/management/commands/test.py", line 33, in handle
failures = test_runner(test_labels, verbosity=verbosity, interactive=interactive) File "/opt/local/lib/python2.5/site-packages/django_test_coverage-0.1-py2.5.egg/django-test-coverage/runner.py", line 58, in run_tests
modules.extend(_package_modules(*pkg)) File "/opt/local/lib/python2.5/site-packages/django_test_coverage-0.1-py2.5.egg/django-test-coverage/runner.py", line 92, in _package_modules
modules.append(__import__(impstr + '.' + name, {}, {}, [''])) File "/Users/oleg/jin/goclub/trunk/jin/goserver/admin.py", line 11, in <module>
admin.site.register(ActiveList, ActiveListAdmin) File "/opt/local/lib/python2.5/site-packages/Django-1.0.2_final-py2.5.egg/django/contrib/admin/sites.py", line 64, in register
raise AlreadyRegistered('The model %s is already registered' % model.__name__) django.contrib.admin.sites.AlreadyRegistered: The model ActiveList is already registered silver:jin oleg$
Admin file looks like this:
from goserver.models import ActiveList, Game
from django.contrib import admin
class ActiveListAdmin(admin.ModelAdmin):
list_display = ('user', "is_Bot", "isActive")
admin.site.register(ActiveList, ActiveListAdmin)
admin.site.register(Game)
I run it all this way:
python manage.py test goserver
Also noticed that if I remove lines
c = Client()
response = c.post('/')
from a test case definition, then no error appears
Looking at the traceback, it looks like you have an app called django_test_coverage-0.1 which is importing your app's admin.py.
It is probably importing it from a different location, such as yourproject.yourapp.admin as opposed to yourapp.admin. Since it's technically seen as a different module, it is re-imported and the admin.site.register calls are made again. This causes the AlreadyRegistered error.
My suggestion would be to remove django_test_coverage app (or fix it).
My questions,
I don't see what is base type/class for TestCase - is it Django Test one, or from Unittest?
it is better to use from Django
How are you runnig test? using Django internal test command, by nose, by unittest? By Traceback I thing test command, but I am not quite sure.
What is you definitions for ActiveAdminList and ActiveList? Have you got maybe class Admin in Meta?
I solve this commenting the admin.autodiscover() line in the proye