Python Django NameError: name 'model' is not defined - python

I have a model in one of my apps which is throwing an error when I run "python.py makemigrations signup." I have spent the last two days pouring through documentation (and Google) trying to figure out why this error is happening. Unfortunately I have come up with nothing.
What I am trying to do is include an app in my project. The app sits in the root directory of my python directory (not in a subfolder of of my project). Here is my code:
from django.db import models
class CompanyInfo(models.Model):
companyID = model.AutoField(primary_key=True)
companyName = model.CharField(max_length=100)
companyURL = model.URLField(max_length=100)
companyEmail = model.EmailField(max_length=254)
companyFEIN = model.CharField(max_length=50)
companyUsername= model.CharField(max_length=100)
companyPassword = model.CharField(max_length=100)
class CompanyContact(models.Model):
ccID = model.AutoField(primary_key=True)
ccFirstName = model.CharField(max_length=100)
ccLastName = model.CharField(max_length=100)
ccEmail = model.EmailField(max_length=254)
ccPhone = model.IntegerField(max_length=20)
The exact error that is printed to the console reads:
root#ubuntu1204:/home/humanoid# python manage.py makemigrations humanoid
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 312, in execute
django.setup()
File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/humanoid/signup/models.py", line 3, in <module>
class CompanyInfo(models.Model):
File "/home/humanoid/signup/models.py", line 4, in CompanyInfo
companyID = model.AutoField(primary_key=True)
NameError: name 'model' is not defined

It looks like you have dropped the 's' on models. You need to change your use of model to models.
For example:
companyID = model.AutoField(primary_key=True)
Needs to be:
companyID = models.AutoField(primary_key=True)

It looks like from the import it should be models (plural) and not model.

Related

Flask(flask db init): AttributeError: module 'time' has no attribute 'clock'

While following a Flask tutorial I stumbled around this very strange problem! While setting up the Migrate directory , after the first step of setting the flask app using set FLASK_APP=sql1.py, when I ran this command flask db init I got this error:
(first_flask_env) C:\Users\aakash\Desktop\python programs>flask db init
Traceback (most recent call last):
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Users\aakash\Anaconda3\envs\first_flask_env\Scripts\flask.exe\__main__.py", line 7, in <module>
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\flask\cli.py", line 894, in main
cli.main(args=args, prog_name=name)
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\flask\cli.py", line 557, in main
return super(FlaskGroup, self).main(*args, **kwargs)
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\click\core.py", line 697, in main
rv = self.invoke(ctx)
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\click\core.py", line 1061, in invoke
cmd_name, cmd, args = self.resolve_command(ctx, args)
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\click\core.py", line 1100, in resolve_command
cmd = self.get_command(ctx, cmd_name)
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\flask\cli.py", line 500, in get_command
self._load_plugin_commands()
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\flask\cli.py", line 496, in _load_plugin_commands
self.add_command(ep.load(), ep.name)
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\pkg_resources\__init__.py", line 2472, in load
return self.resolve()
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\pkg_resources\__init__.py", line 2478, in resolve
module = __import__(self.module_name, fromlist=['__name__'], level=0)
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\flask_migrate\__init__.py", line 8, in <module>
from alembic import __version__ as __alembic_version__
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\alembic\__init__.py", line 8, in <module>
from . import op # noqa
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\alembic\op.py", line 1, in <module>
from .operations.base import Operations
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\alembic\operations\__init__.py", line 1, in <module>
from .base import Operations, BatchOperations
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\alembic\operations\base.py", line 3, in <module>
from .. import util
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\alembic\util\__init__.py", line 6, in <module>
from .pyfiles import ( # noqa
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\alembic\util\pyfiles.py", line 6, in <module>
from mako.template import Template
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\mako\template.py", line 10, in <module>
from mako.lexer import Lexer
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\mako\lexer.py", line 11, in <module>
from mako import parsetree, exceptions, compat
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\mako\parsetree.py", line 9, in <module>
from mako import exceptions, ast, util, filters, compat
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\mako\exceptions.py", line 11, in <module>
from mako import util, compat
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\mako\util.py", line 11, in <module>
from mako import compat
File "c:\users\aakash\anaconda3\envs\first_flask_env\lib\site-packages\mako\compat.py", line 124, in <module>
time_func = time.clock
AttributeError: module 'time' has no attribute 'clock'
I'm getting the exact same error while running my .py script also,here's the script:
from flask import Flask
import os
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
basedir = os.path.abspath(os.path.dirname(__file__)) #Full directory path of the file I'm working with..here, sql1.py
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
Migrate(app,db) #Here it connect the application "app.py"
# with the database "db"
class puppy(db.Model):
__tablename__ = 'Name Provided by me!!'
id = db.Column(db.Integer,primary_key = True)
name = db.Column(db.Text)
age = db.Column(db.Integer)
def __init__(self,name,age):
self.name = name
self.age = age
def __repr__(self):
return f"puppy {self.name} is {self.age} year/s old!"
I looked into every solution I found (here and this)and made sure everything was correct! I ran this command when my environment was activated which had installed every package needed including SQLAlchemy and Flask-Migrate.
I even deleted them (packages) and re-installed their latest versions but still getting the same error!
I'm using Python 3.8.5
You have some dependencies that are too old and incompatible with Python 3.8. At the very least, you should update the mako package:
pip install --upgrade mako
I had a similar issue I had to update flask_sqlalchemy even after doing this I had issues. I ended up having to make a new virtual environment, I would make a small hello world project on another virtual environment to see if that works.
For me, it was giving the same error, so I removed __init__.py file from the folder which has app.py
After removing I ran the
flask init db
it worked :)

AttributeError: module 'profile' has no attribute 'run'

So I have an extended User model (extended AbstractUser) called Profile. This was in a seperate app called "profiles". I was plugging in the standard login and realised it was looking for a "profile" app name as standard, so I renamed it (directories, code, DB schema) which I thought should work. app_name was actually already set to "profile" in apps.py, so didn't need to rename url references.
No dice. I get the error in the title.
So I removed all migrations (I'm at the stage where I can still do this OK :) ) and deleted the sqlite DB that I'm currently working with, thinking I'd just rerun the migrations and recreate everything.
Same error.
The stack trace is:
λ python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\base.py", line 361, in execute
self.check()
File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\base.py", line 390, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\management\base.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\debug_toolbar\apps.py", line 18, in check_middleware
from debug_toolbar.middleware import DebugToolbarMiddleware
File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\debug_toolbar\middleware.py", line 12, in <module>
from debug_toolbar.toolbar import DebugToolbar
File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\debug_toolbar\toolbar.py", line 141, in <module>
urlpatterns = DebugToolbar.get_urls()
File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\debug_toolbar\toolbar.py", line 134, in get_urls
for panel_class in cls.get_panel_classes():
File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\debug_toolbar\toolbar.py", line 116, in get_panel_classes
import_string(panel_path) for panel_path in dt_settings.get_panels()
File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\debug_toolbar\toolbar.py", line 116, in <listcomp>
import_string(panel_path) for panel_path in dt_settings.get_panels()
File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\django\utils\module_loading.py", line 17, in import_string
module = import_module(module_path)
File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "C:\Users\mjnic\.virtualenvs\pyp-E_0Se9Bl\lib\site-packages\debug_toolbar\panels\profiling.py", line 1, in <module>
import cProfile
File "D:\Python\Python37-32\Lib\cProfile.py", line 22, in <module>
run.__doc__ = _pyprofile.run.__doc__
AttributeError: module 'profile' has no attribute 'run'
What have I missed as part of this rename?
Any other info I've missed posting that would help? (I've searched for any instance of "profiles", but everything is correctly renamed now, and the app was working OK prior to this, so it's purely this rename that's messed it up).
Edit: Can it be that "profile" conflicts with some internal python routine? That cProfile.py file under the python installation is defined as
#! /usr/bin/env python3
"""Python interface for the 'lsprof' profiler.
Compatible with the 'profile' module.
"""
Now that can't be anything to do with my project? Do I just need to call my app/extended user model something other than "profile"?
OK. So yes, it's a naming clash. I've renamed my "Profile" model and "profile" app as "UserProfile" and "user_profile" and updated everything accordingly. It all seems to work now ...
Just putting an answer here in case anybody comes along in the future with the same issue!
In my case, it was profile.py file.
Delete the file and try again.
In my case was the conflict between app - 'profile' and 'django-debug-toolbar':
I rename my app from 'profile' to 'account' and it solved the problem

'type' object is not iterable in using django_enums

I tried to use django_enums and got an error with list(cls) when making migrations:
(venv:SFS)rita#rita-notebook:~/Serpentarium/ServiceForServices/project/serviceforservices$ python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/rita/Serpentarium/ServiceForServices/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/rita/Serpentarium/ServiceForServices/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute
django.setup()
File "/home/rita/Serpentarium/ServiceForServices/venv/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/rita/Serpentarium/ServiceForServices/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/rita/Serpentarium/ServiceForServices/venv/local/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/rita/Serpentarium/ServiceForServices/project/serviceforservices/service/models.py", line 84, in <module>
class EmployeesStatus(models.Model):
File "/home/rita/Serpentarium/ServiceForServices/project/serviceforservices/service/models.py", line 86, in EmployeesStatus
status = enum.EnumField(StatusEnum, default=StatusEnum.AT)
File "/home/rita/Serpentarium/ServiceForServices/venv/local/lib/python2.7/site-packages/django_enums/enum.py", line 53, in __init__
kwargs['max_length'] = self.enum.get_max_length()
File "/home/rita/Serpentarium/ServiceForServices/venv/local/lib/python2.7/site-packages/django_enums/enum.py", line 39, in get_max_length
return len(max(list(cls), key=(lambda x: len(x.key))).key)
TypeError: 'type' object is not iterable
I installed django-enums, enum and six:
(venv:SFS)rita#rita-notebook:~/Serpentarium/ServiceForServices/project/serviceforservices$ pip install django-enums
(venv:SFS)rita#rita-notebook:~/Serpentarium/ServiceForServices/project/serviceforservices$ pip install enum
(venv:SFS)rita#rita-notebook:~/Serpentarium/ServiceForServices/project/serviceforservices$ pip install six
Using in Models.py:
...
from django_enums import enum
...
class StatusEnum(enum.Enum):
__order__ = 'AT BT BC AC' # for python 2
AT = (u'АВ', u'Активен временно')
BT = (u'БВ', u'Блокирован временно')
BC = (u'БП', u'Блокирован постоянно')
AC = (u'АП', u'Активен постоянно')
class EmployeesStatus(models.Model):
name = models.CharField(max_length=128)
status = enum.EnumField(StatusEnum, default=StatusEnum.AT)
It seems like project is alive, it also was updated for Django 1.10 and compartible with python 2 allegedly. So, what I'm doing wrong?
It looks like you are trying to use the backported enum from the 3.4 stdlib, but you installed enum -- you need to install enum34.

Django 1.9 django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet

Trying to use django-shopify-sync in a Django 1.9 project. When loading the config for the app it gives me the following error, likely because it's trying to load some models in the config?
Tried moving the the two imports that eventually import models into the ready() function below, but still getting the same error. Culpirt lines 2 and 3 in the following file https://github.com/andresdouglas/django-shopify-sync/blob/master/shopify_sync/apps.py
The error is:
$ python manage.py runserver
Unhandled exception in thread started by <function wrapper at 0x10753e500>
Traceback (most recent call last):
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/apps/config.py", line 116, in create
mod = import_module(mod_path)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/andres/.virtualenvs/[...]/src/shopify-sync/shopify_sync/apps.py", line 2, in <module>
from shopify_sync.handlers import webhook_received_handler
File "/Users/andres/.virtualenvs/[...]/src/shopify-sync/shopify_sync/handlers.py", line 3, in <module>
from .models import (CustomCollection, Customer, Order, Product, Shop,
File "/Users/andres/.virtualenvs/[...]/src/shopify-sync/shopify_sync/models/__init__.py", line 3, in <module>
from .address import Address
File "/Users/andres/.virtualenvs/[...]/src/shopify-sync/shopify_sync/models/address.py", line 6, in <module>
from .base import ShopifyResourceModel
File "/Users/andres/.virtualenvs/[...]/src/shopify-sync/shopify_sync/models/base.py", line 144, in <module>
class ShopifyResourceModel(models.Model):
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/db/models/base.py", line 94, in __new__
app_config = apps.get_containing_app_config(module)
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/apps/registry.py", line 239, in get_containing_app_config
self.check_apps_ready()
File "/Users/andres/.virtualenvs/[...]/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
UPDATE: If I move the following lines (model imports) https://github.com/andresdouglas/django-shopify-sync/blob/master/shopify_sync/handlers.py#L3-L4 to inside get_topic_models it seems to fix the error. But that's kind of dirty, can anyone come up with a better solution?
If you move the following lines (model imports) https://github.com/andresdouglas/django-shopify-sync/blob/master/shopify_sync/handlers.py#L3-L4
from .models import (CustomCollection, Customer, Order, Product, Shop,
SmartCollection)
inside get_topic_models it seems to fix the error. But that's kind of dirty, can anyone come up with a better solution?
It looks like you may have an ordering issue. Make sure your application is in the INSTALLED_APPS tuple after django-shopify-sync. You can find a few more details in the Application registry documentation.
As unsatisfying as an inline import is, you may be stuck with it. I'd suggest moving
from shopify_sync.handlers import webhook_received_handler
from shopify_webhook.signals import webhook_received
into the ready method in apps.py. This will delay the import until the models are ready.
The change I tried is:
diff --git a/shopify_sync/apps.py b/shopify_sync/apps.py
index 663b43b..0bc1fcc 100644
--- a/shopify_sync/apps.py
+++ b/shopify_sync/apps.py
## -1,7 +1,5 ##
from django.apps import AppConfig
-from shopify_sync.handlers import webhook_received_handler
-from shopify_webhook.signals import webhook_received
-
+import importlib
class ShopifySyncConfig(AppConfig):
"""
## -16,5 +14,9 ## class ShopifySyncConfig(AppConfig):
The ready() method is called after Django setup.
"""
+ signals_webhook_received = importlib.import_module('.signals', package='shopify_webhook')
+ handlers_webhook_received_handler = importlib.import_module('.handlers', package='shopify_sync')
+
# Connect shopify_webhook's webhook_received signal to our synchronisation handler.
- webhook_received.connect(webhook_received_handler, dispatch_uid = 'shopify_sync_webhook_received_handler')
+ signals_webhook_received.webhook_received.connect(handlers_webhook_received_handler.webhook_received_handler, dispatch_uid = 'shopify_sync_webhook_received_handler')
+

how to use wysiwyg-editor?

please help to solve the problem.
I'm trying to use wysiwyg-Editor:
https://github.com/divio/djangocms-text-ckeditor
models.py:
from django.db import models
from djangocms_text_ckeditor.fields import HTMLField
class News(models.Model):
text = models.HTMLField(
'Основной текст',
max_length=50000,
blank=False,
)
settings.py:
INSTALLED_APPS = (
'djangocms_text_ckeditor',
)
when trying to use the command:
python manage.py schemamigration app_news --auto
I get the following error message:
File "/home/kalinins/.virtualenvs/blogik5/local/lib/python2.7/site-packages/django/conf/__init__.py", line 49, in _setup
self._wrapped = Settings(settings_module)
File "/home/kalinins/.virtualenvs/blogik5/local/lib/python2.7/site-packages/django/conf/__init__.py", line 128, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/home/kalinins/.virtualenvs/blogik5/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/home/kalinins/.virtualenvs/blogik5/blogik5/settings.py", line 149, in <module>
mod = import_module(app)
NameError: name 'import_module' is not defined
The error doesn't seem to have anything to do with wsyiwyg-editor: you are calling import_module(app) in your settings.py file, but have not defined or imported that function in that file.

Categories

Resources