django error: __init__() takes exactly 1 argument (2 given) - django

I've written a sqlalchemy model called 'library':
class Library(Base):
__tablename__ = 'library'
id = Column(Integer, primary_key=True)
details = Column(String)
def __init__(self, details):
self.details = details
def __repr__(self):
return u"Library(%s)" % (self.details)
Then, inside the views.py file, I've written:
def is_lib_empty():
return len(session.query(Library).all()) <= 0
def populateLib():
new_libs = [Library('one'), Library('two'), Library('three'), Library('four')]
session.add_all(new_libs)
session.commit()
def index(request):
if is_lib_empty():
populateLib()
libs = session.query(Library).all()
return render_to_response('../templates/index.html',{'libs':libs})
And then I run python manage.py runserver, and it shows me an error message:
__init__() takes exactly 1 argument (2 given)
What should I do to fix this?
TypeError at /
__init__() takes exactly 1 argument (2 given)
Request Method: GET
Django Version: 1.3.1
Exception Type: TypeError
Exception Value:
__init__() takes exactly 1 argument (2 given)
Exception Location: /cs/wetlab/Limor/workspace/Yeasti/Yeasti/loose_coupling/../loose_coupling/with_sqlalchemy/views.py in populateLib, line 25
Python Executable: /sw/bin/python2.7
Python Version: 2.7.2
Python Path:
['/cs/wetlab/Limor/workspace/Yeasti/Yeasti/loose_coupling',
'/sw/lib/python27.zip',
'/sw/lib/python2.7',
'/sw/lib/python2.7/plat-darwin',
'/sw/lib/python2.7/plat-mac',
'/sw/lib/python2.7/plat-mac/lib-scriptpackages',
'/sw/lib/python2.7/lib-tk',
'/sw/lib/python2.7/lib-old',
'/sw/lib/python2.7/lib-dynload',
'/sw/lib/python2.7/site-packages',
'/sw/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg-info']
Server time: Sun, 1 Jul 2012 05:50:03 -0500
Environment:
Request Method: GET
Django Version: 1.3.1
Python Version: 2.7.2
Installed Applications:
['loose_coupling.with_sqlalchemy']
Installed Middleware:
('django.middleware.common.CommonMiddleware',)
Traceback:
File "/sw/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/cs/wetlab/Limor/workspace/Yeasti/Yeasti/loose_coupling/../loose_coupling/with_sqlalchemy/views.py" in index
39. populateLib()
File "/cs/wetlab/Limor/workspace/Yeasti/Yeasti/loose_coupling/../loose_coupling/with_sqlalchemy/views.py" in populateLib
25. new_libs = [Library('one'), Library('two'), Library('three'), Library('four')]
Exception Type: TypeError at /
Exception Value: __init__() takes exactly 1 argument (2 given)

UPDATE:
You can always use the default constructor, using keyword arguments:
Library(details='some details')
as described in http://docs.sqlalchemy.org/en/rel_0_7/orm/tutorial.html
This is supported by the default constructor, no need to override it. Anyway, your code should work, unless there is some override somewhere...

Related

'DeferredAttribute' object is not callable

I'm working on a simple django project, but i face this problem that you see below so, i want a solution because i really got tired
I expect the output of that code to be numberone but the actual output is this error :
TypeError at /db/
'DeferredAttribute' object is not callable
Request Method: GET
Request URL: http://127.0.0.1:8000/db/
Django Version: 2.1.5
Exception Type: TypeError
Exception Value:
'DeferredAttribute' object is not callable
Exception Location: /home/mohammed/Desktop/New life programming/python /pythonDjano/Filecorse/NewDjango/MohammedAlaa/Abdullah/views.py in db, line 16
Python Executable: /usr/bin/python3
Python Version: 3.6.8
Python Path:
['/home/mohammed/Desktop/New life '
'programming/python/pythonDjano/Filecorse/NewDjango/MohammedAlaa',
'/usr/local/lib/python3.6/dist-packages/pip-19.1.1-py3.6.egg',
'/usr/lib/python36.zip',
'/usr/lib/python3.6',
'/usr/lib/python3.6/lib-dynload',
'/home/mohammed/.local/lib/python3.6/site-packages',
'/usr/local/lib/python3.6/dist-packages',
'/usr/lib/python3/dist-packages']
Server time: Sat, 31 Aug 2019 11:13:18 +0000
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Product
def Home(request):
return HttpResponse('Welcome, Mohammed Alaa :)')
def htm(request):
return render(request,'htm.html',{'hello':"hello Mohammed Abo Alaa again:)", 'days':['wed', 'fri', 'thru']
})
def others(request):
return HttpResponse('Welcome, Mohammed Alaa :) form others')
def db(request):
dat = ''
p1 = Product(namee='numberone', pricee=500,Type='m')
p1.save()
dat = Product.namee()
return HttpResponse(dat)
You need to refer to the Product instance you just created, not the whole Product class. And it's just a string, no need to call it.
dat = p1.namee

I am using django haystack with whoosh , But there some error after entering some search query in searchbar, below is the description

Error screenshot
AttributeError at /search/
'NoneType' object has no attribute '_default_manager'
Request Method: GET
Request URL: http://127.0.0.1:8000/search/?q=desktop
Django Version: 1.9
Exception Type: AttributeError
Exception Value:'NoneType' object has no attribute '_default_manager'
Exception Location: /home/ankit/venv/django/lib/python3.4/site-packages/haystack/query.py in post_process_results, line 219
Python Executable: /home/ankit/venv/django/bin/python
Python Version: 3.4.3
Python Path: ['/home/ankit/venv/django/p2',
'/home/ankit/venv/django/lib/python3.4',
'/home/ankit/venv/django/lib/python3.4/plat-x86_64-linux-gnu',
'/home/ankit/venv/django/lib/python3.4/lib-dynload',
'/usr/lib/python3.4',
'/usr/lib/python3.4/plat-x86_64-linux-gnu',
'/home/ankit/venv/django/lib/python3.4/site-packages']
Server time: Sun, 27 Dec 2015 10:29:28 +0000
My search_indexes.py
import datetime
from haystack import indexes
from inventory.models import Item
class ItemIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
pub_date = indexes.DateTimeField(model_attr='pub_date')
content_auto = indexes.EdgeNgramField(model_attr='title')
def get_model(self):
return Item
def index_queryset(self, using=None):
return self.get_model().objects.all()
My settings.py file
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
},
}
The django.db.model.get_model is not available any longer in 1.9, so None is returned when calling django.db.models.get_model, but in the more recent commit (from the 3rd of January) the utils.app_loading.py is used to either use the django.apps.apps.get_model when using Django 1.7 or higher, otherwise the old django.db.models._get_models is used.
So, best to upgrade to the latest development version git+https://github.com/django-haystack/django-haystack.git.

Django import-export import button throws mysterious TypeError

I've been trying to get django-import-export working with the admin page of my site, but have run into a brick wall. Currently I'm working with an empty database (schema have been created from Models, but no data have been added). The "export" button seems to work fine, but clicking the import button throws a TypeError which I can't decipher for the life of me. Here it is:
TypeError at /admin/new_bridge/wordtable/import/
__init__() takes exactly 3 arguments (1 given)
Request Method: GET
Request URL: http://localhost:8000/admin/new_bridge/wordtable/import/
Django Version: 1.8.3
Exception Type: TypeError
Exception Value:
__init__() takes exactly 3 arguments (1 given)
Exception Location: /usr/local/lib/python2.7/dist-packages/import_export/admin.py in import_action, line 178
Python Executable: /usr/bin/python
Python Version: 2.7.6
Python Path:
['/home/jack/ds/bridge-repo',
'/opt/ros/indigo/lib/python2.7/dist-packages',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PILcompat',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/pymodules/python2.7',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
'/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode',
'/opt/new_bridge/']
Server time: Fri, 17 Jul 2015 15:38:33 -0500
And here's the Traceback for that error:
Environment:
Request Method: GET
Request URL: http://localhost:8000/admin/new_bridge/wordtable/import/
Django Version: 1.8.3
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'new_bridge',
'import_export')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
110. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner
233. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/import_export/admin.py" in import_action
178. resource = self.get_import_resource_class()()
Exception Type: TypeError at /admin/new_bridge/wordtable/import/
Exception Value: __init__() takes exactly 3 arguments (1 given)
If it helps, I tried importing via manage.py shell (referencing the docs), and it worked. Here's what I did:
import tablib
from import_export import resources
from new_bridge.models import *
book_resource = resources.modelresource_factory(model=WordTable)()
dataset = tablib.Dataset(['1', 'title'], headers=['id','title'])
result = book_resource.import_data(dataset, dry_run=False)
print result.has_errors()
False
Here is the model in question (from models.py):
class WordTable(models.Model):
id = models.IntegerField(primary_key=True)
title = models.CharField(db_column='TITLE', max_length=17, blank=True)
def __unicode__(self):
return self.title
class Meta:
managed = True
db_table = 'word_table'
...and the relevant portions of manage.py:
from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from import_export import resources
from new_bridge.models import WordTable
class WordTableResource(ImportExportModelAdmin):
class Meta:
model = WordTable
fields = ('title')
class WordTableAdmin(ImportExportModelAdmin):
fields = ['title']
resource_class = WordTableResource
pass
# Register models w admin to make them editable:
admin.site.register(WordTable, WordTableAdmin)
This has really thrown me through a loop. Any help would be much appreciated.
Your WordTableResource class is inheriting from ImportExportModelAdmin instead of resources.ModelResource.

Pillow on Heroku doesn't work

I'm developing an application with Django1.4.3 and Pillow2.0.0.
I have a form to upload image file.
After resizing and cropping posted image file,
I want to save the image file, but error occur.
In django's local test server, error doesn't occur and work well,
but in Heroku, error occur.
Would you tell me some advice?
The code receiving posted image is below.
In addition, I use S3boto and django-storage.
def edit_photo(request):
if request.user.is_authenticated():
if request.method == 'POST':
# save posted image as UserProfile.image temporarily
posted_photo = request.FILES['posted_photo']
file_content = ContentFile(posted_photo.read())
profile = request.user.get_profile()
temp_filename = "new_file_"+str(profile.id)+"_"+posted_photo.name
profile.image.save(temp_filename, file_content)
# read posted file
data = profile.image.read()
im = Image.open(StringIO.StringIO(data))
# crop posted image
cropping_box = (10, 10, 300, 300)
photo = photo.crop(cropping_box)
photo_comp = photo.resize((230, 230), Image.ANTIALIAS)
# save the image
thum = StringIO.StringIO()
photo_comp.save(thum, "png")
profile.image.save("saved_image_"+str(profile.id)+".png",ContentFile(thum.getvalue()))
# delete temporary image
default_storage.delete("faces/"+temp_filename)
return redirect('../')
And Error message is like this.
TypeError at /manage/edit_photo
function takes at most 4 arguments (6 given)
Request Method: POST
Request URL: http://hogehoge.herokuapp.com/manage/edit_photo
Django Version: 1.4.3
Exception Type: TypeError
Exception Value:
function takes at most 4 arguments (6 given)
Exception Location: /app/.heroku/python/lib/python2.7/site-packages/PIL/Image.py in _getencoder, line 395
Python Executable: /app/.heroku/python/bin/python
Python Version: 2.7.4
Python Path:
['/app',
'/app/.heroku/python/lib/python2.7/site-packages/pip-1.3.1-py2.7.egg',
'/app/.heroku/python/lib/python2.7/site-packages/newrelic-1.11.0.55/newrelic/bootstrap',
'/app',
'/app/.heroku/python/lib/python27.zip',
'/app/.heroku/python/lib/python2.7',
'/app/.heroku/python/lib/python2.7/plat-linux2',
'/app/.heroku/python/lib/python2.7/lib-tk',
'/app/.heroku/python/lib/python2.7/lib-old',
'/app/.heroku/python/lib/python2.7/lib-dynload',
'/app/.heroku/python/lib/python2.7/site-packages',
'/app/.heroku/python/lib/python2.7/site-packages/PIL',
'/app/.heroku/python/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg-info']
/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py in get_response
response = callback(request, *callback_args, **callback_kwargs) ...
▶ Local vars
/app/movie_manager/views.py in edit_photo
photo_comp.save(thum, "png") ...
▶ Local vars
/app/.heroku/python/lib/python2.7/site-packages/PIL/Image.py in save
save_handler(self, fp, filename) ...
▶ Local vars
/app/.heroku/python/lib/python2.7/site-packages/PIL/PngImagePlugin.py in _save
ImageFile._save(im, _idat(fp, chunk), [("zip", (0,0)+im.size, 0, rawmode)]) ...
▶ Local vars
/app/.heroku/python/lib/python2.7/site-packages/PIL/ImageFile.py in _save
e = Image._getencoder(im.mode, e, a, im.encoderconfig) ...
▶ Local vars
/app/.heroku/python/lib/python2.7/site-packages/PIL/Image.py in _getencoder
return encoder(mode, *args + extra) ...
▶ Local vars
For anyone else who finds this problem...
This TypeError can occur when PIL and Pillow are installed simultaneously (perhaps inadvertently due to hidden package requirements). You'll need to uninstall both PIL and Pillow and reinstall just the one you want.

500-error when adding a picture

In Django-CMS, I select the picture plugin and add a picture from my harddrive, then when I click on that picture-plugin I get the error as seen below. What is the reason for this?
ValueError at /admin/cms/page/2/edit-plugin/7/cms_page_media/2/parking_mockup.png/
invalid literal for int() with base 10: '2/edit-plugin/7/cms_page_media/2/parking_mockup.png'
Request Method: GET
Request URL: http://localhost:8000/admin/cms/page/2/edit-plugin/7/cms_page_media/2/parking_mockup.png/
Django Version: 1.3.1
Exception Type: ValueError
Exception Value:
invalid literal for int() with base 10: '2/edit-plugin/7/cms_page_media/2/parking_mockup.png'
Exception Location: C:\Python27\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 479
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
Python Path:
['C:\\djangoworkspace\\hulawai',
'C:\\Python27\\lib\\site-packages\\django_classy_tags-0.3.4.1-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\django_sekizai-0.5-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\html5lib-0.95-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\virtualenv-1.7.1.2-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\pip-1.1-py2.7.egg',
'C:\\Windows\\system32\\python27.zip',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'C:\\Python27\\lib\\site-packages\\PIL']
Server time: Thu, 22 Mar 2012 11:03:58 +0100
Traceback Switch to copy-and-paste view
C:\Python27\lib\site-packages\django\core\handlers\base.py in get_response
for middleware_method in self._view_middleware:
response = middleware_method(request, callback, callback_args, callback_kwargs)
if response:
break
if response is None:
try:
response = callback(request, *callback_args, **callback_kwargs) ...
except Exception, e:
# If the view raised an exception, run it through exception
# middleware, and if the exception middleware returns a
# response, use that. Otherwise, reraise the exception.
for middleware_method in self._exception_middleware:
response = middleware_method(request, e)
UPDATE Full stacktrace available here: https://gist.github.com/2157837
I edited my settings.py
From
MEDIA_URL = 'media/'
To
MEDIA_URL = 'http://localhost:8000/media/'