Why is Django unable to run properly? - python

I am recently working on Django following the description from the book Python Crash Course. I followed every step and tried to restart from the beginning a couple of times, still unable to solve the problem(Even reinstalled MacOS to get a cleaner desktop). Here is my code:
class Topic(models.Model):
'''A topic the user is learning about'''
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
'''Return a string represent model'''
return self.text
The tracebacks are below:
Traceback (most recent call last):
File "/Users/bryan/Desktop/python/learning_log/learning_logs/models.py", line 3, in <module>
class Topic(models.Model):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/base.py", line 108, in __new__
app_config = apps.get_containing_app_config(module)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 253, in get_containing_app_config
self.check_apps_ready()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 135, in check_apps_ready
settings.INSTALLED_APPS
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/conf/__init__.py", line 82, in __getattr__
self._setup(name)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/conf/__init__.py", line 63, in _setup
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
[Finished in 304ms with exit code 1]
[cmd: ['python3', '-u', '/Users/bryan/Desktop/python/learning_log/learning_logs/models.py']]
[dir: /Users/bryan/Desktop/python/learning_log/learning_logs]
[path: /Library/Frameworks/Python.framework/Versions/3.10/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin]
Edit:
The code is in the file models.py

It seems like the error is happening because you're running the models.py file directly. In working with Django, you rarely run a .py file directly. Usually you run some commands in the terminal, and then you interact with your project in a browser.
Are you working in an active virtual environment?
Have you run the makemigrations command for your app?
Have you run python manage.py migrate?
What happens when you run python manage.py runserver?

There is small mistake you are trying to access the text in __str__ method and due to which it failed in order to access the text you need to change the code like self.text
def __str__(self):
'''Return a string represent model'''
return self.text

Related

Error from Tasks job when referencing a model that uses from django.contrib.auth.models import User

My blog.models is using:
from django.contrib.auth.models import User
That model is being called from my script which I run as a task every hour. Here's the error that I'm seeing:
Traceback (most recent call last):
File "/home/redinv/src/cron.py", line 8, in <module>
from blog.models import ImagePost, MyPost, ScheduledPost
File "/home/redinv/src/blog/models.py", line 3, in <module>
from django.contrib.auth.models import User
File "/usr/lib/python3.8/site-packages/django/contrib/auth/models.py", line 2, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "/usr/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 47, in <module>
class AbstractBaseUser(models.Model):
File "/usr/lib/python3.8/site-packages/django/db/models/base.py", line 103, in __new__
app_config = apps.get_containing_app_config(module)
File "/usr/lib/python3.8/site-packages/django/apps/registry.py", line 252, in get_containing_app_config
self.check_apps_ready()
File "/usr/lib/python3.8/site-packages/django/apps/registry.py", line 134, in check_apps_ready
settings.INSTALLED_APPS
File "/usr/lib/python3.8/site-packages/django/conf/__init__.py", line 79, in __getattr__
self._setup(name)
File "/usr/lib/python3.8/site-packages/django/conf/__init__.py", line 60, in _setup
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
2020-06-25 00:50:25 -- Completed task, took 3.95 seconds, return code was 1.
In my settings file under INSTALLED_APPS =, I already have:
'django.contrib.auth',
This code is of course working locally on my machine and I'm trying to figure what's the issue here?
I tried running that script from two locations to see if there was an issue trying to find the import files:
/home/username/src
/home/username/src/blog
Same result for both.
Any assistance is appreciate it, I'm pretty new at python.
Thanks
If you want to run Django code from outside the context of a website, you need to initialize Django first. There are two ways to do that:
Run the setup function to set things up; this part of the Django docs explains how to do that
Change the code that you want to run in your task into a management command. This is a little more work, but I would recommend it as a better option in the long term.

django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB LESPACE, but settings are not configured

I’m using Django 1.9.1 with Python 3.5.2 and I'm having a problem running a Python script that uses Django models.
C:\Users\admin\trailers>python load_from_api.py
Traceback (most recent call last):
File "load_from_api.py", line 6, in <module>
from movies.models import Movie
File "C:\Users\admin\trailers\movies\models.py", line 5, in <module>
class Genre(models.Model):
File "C:\Users\admin\trailers\movies\models.py", line 6, in Genre
id = models.CharField(max_length=10, primary_key=True)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\fi
elds\__init__.py", line 1072, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\fi
elds\__init__.py", line 166, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\conf\__init_
_.py", line 55, in __getattr__
self._setup(name)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\conf\__init_
_.py", line 41, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB
LESPACE, but settings are not configured. You must either define the environment
variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing s
ettings.
here's the script:
#!/usr/bin/env python
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trailers.settings")
os.environ["DJANGO_SETTINGS_MODULE"] = "trailers.settings"
import django
django.setup()
import tmdbsimple as tmdb
from movies.models import Movie
#some code...
I can't really figure out what's wrong. Any help is appreciated!
I figured out how to run it without changing the script and that's by using
python manag.py shell
and then
exec(open('filename').read())
that seemed to work just fine.
I would recommend using Django Custom Management Commands - they are really simple to use, they use your settings, your environment, you can pass parameters and also you can write help strings so you can use --help
Then you just call it with ./manage.py my_custom_command
Or if you just want to run your script add this to the your script
project_path = '/home/to/your/trailers/project/src'
if project_path not in sys.path:
sys.path.append(project_path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trailers.common")
import django
django.setup()

Django Help - Basic Setup and Basic Functionality

Done my due diligence and still having issues. Here is my goal. I'm using Django with Python to create a website with some custom coded features. The problem I'm having is this. I've tried these tutorials: http://matthewdaly.co.uk/blog/2013/12/28/django-blog-tutorial-the-next-generation-part-1/
http://ferretfarmer.net/2013/09/05/tutorial-real-time-chat-with-django-twisted-and-websockets-part-1/ (would prefer to use just django and no twisted but open to anything.
Next to last is: http://www.djangorocks.com/tutorials/how-to-create-a-basic-blog-in-django/starting-your-application.html for blogs
And finally: creating a company site with blog, news pasting, etc. Most of which I can get via models as i have done in the past.
I've made progress: But I'm stuck at this part. When I try to run python manage.py runserver i get a huge error like this:
ages\django\conf\__init__.py", line 113, in __i nit__
[shenk#LUCY2 mytest]$ python manage.py runserver
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "c:\Python27\lib\site- packages\django\core\management\__init__.py", line
338, in execute_from_command_line
utility.execute()
File "c:\Python27\lib\site-packages\django\core\management\__init__.py", line
330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "c:\Python27\lib\site-packages\django\core\management\__init__.py", line
190, in fetch_command
klass = load_command_class(app_name, subcommand)
File "c:\Python27\lib\site-packages\django\core\management\__init__.py", line
40, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "c:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "c:\Python27\lib\site- packages\django\core\management\commands\runserver.py",
line 14, in <module>
from django.db.migrations.executor import MigrationExecutor
File "c:\Python27\lib\site-packages\django\db\migrations\executor.py", line 6,
in <module>
from .loader import MigrationLoader
File "c:\Python27\lib\site-packages\django\db\migrations\loader.py", line 10,
in <module>
from django.db.migrations.recorder import MigrationRecorder
File "c:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 9,
in <module>
class MigrationRecorder(object):
File "c:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 23
, in MigrationRecorder
class Migration(models.Model):
File "c:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 24
, in Migration
app = models.CharField(max_length=255)
File "c:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line
1081, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "c:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line
161, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "c:\Python27\lib\site-packages\django\conf\__init__.py", line 48, in __ge
tattr__
self._setup(name)
File "c:\Python27\lib\site-packages\django\conf\__init__.py", line 44, in _set
up
self._wrapped = Settings(settings_module)
File "c:\Python27\lib\site-pack
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be
empty.
Please excuse the formatting it is not cooperating 100%, working pretty good though.
Anyway I want to create a site with django and add on to it a bunch of hard coded basic modules which I can do. What I need help with as I believe I mentioned is why I cant do python manage.py runserver? Or the other question I had was the tutorials I found for blogs and such on Django were either out of date or did not work well. Please guide me towards the best way to create a company website with Django. For now I need basic skills similar to word press without and plugins (comments, blog, etc.) I can add more advanced functionality myself once this is working. The info on the Django Doc's only works like 20% of the time.
Any help would be appreciated, my preferred answer is a bit of an explanmation how to use it, as well as what could be causing my runserver issues.
Any response is much appreciated. I know this isn't the place, but send me a message on SO and perhaps we can work out payment in order to learn from you, get the base application done. After that I can write the other modules myself. (Yes, you'll be complicated and you can telecommute as I'm in PA outside Philly.
P.S. I'm an advanced C/C++ dev, a bit of C#, JS, Java, and mainly Python.
If you need any more info I can help. I'm great with python and even .NET MVC but django is a bit different so any guidance is appreciated.
Thanks in advance.
It says you've not configured the SECRET_KEY setting. You need to set the value of the SECRET_KEY variable in your_app_name/settings.py - if you used the command python manage.py startproject to create your Django project, it should have done this for you.
See here: https://docs.djangoproject.com/en/1.8/ref/settings/#secret-key
open settings.py
add
SECRET_KEY = "IWANTDJANGO4SUMREASON"
to the bottom
According to your error log, you've improperly configured your Django application. The SECRET_KEY setting must not be empty. Please check your settings.py which is loaded by manage.py and make sure the SECRET_KEY contains an appropriate value. That should get you somewhere further.
On the other hand, I would suggest reading the official documentation aswell as follow the official tutorial on how to get started. These are more often up-to-date and follow the official guidelines.

Extending Zinnia Entry

i am currently working on a website where i want to use django-blog-zinnia with django-cms. I have to extend the entry by a foreign key to another so i followed the documentation on the zinnia website.
I wrote the zinnia_extra/models.py:
from django.db import models
from zinnia.models_bases.entry import AbstractEntry
class AssociationBlog(AbstractEntry):
association = models.ForeignKey("associations.Association",
blank=True,
default=None,
null=True,
related_name='news')
def __str__(self):
return 'AssociationBlog %s' % self.title
class Meta(AbstractEntry.Meta):
abstract = True
Now i came to the south part wich was a painful lesson of underdocumentation. After several hours of reading several answers here i found out that setting up the south migration modules mean something like this:
SOUTH_MIGRATION_MODULES = {
'zinnia': 'zinnia_extra.migrations.zinnia',
}
After that i added
ZINNIA_ENTRY_BASE_MODEL = 'zinnia_extra.models.AssociationBlog'
and also i built a zinnia_extra/admin.py:
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from zinnia.models.entry import Entry
from zinnia.admin.entry import EntryAdmin
class AssociationBlogAdmin(EntryAdmin):
fieldsets = ((_('Content'), {'fields': (
('title', 'status'), 'content', 'image', 'association')}),) + \
EntryAdmin.fieldsets[1:]
admin.site.unregister(Entry)
admin.site.register(Entry, AssociationBlogAdmin)
(which is like in the documentation)
to the settings.py. South works as expected with an resolved migration error that is actually unresolved. But i managed to get that. But my extra field is not in the Admin area. I searched around and found out that i have to add the extra to the INSTALLED_APPS, so they now look like that:
INSTALLED_APPS = (
... ,
'zinnia',
'cmsplugin_zinnia',
'zinnia_ckeditor',
'zinnia_extra'
)
which is actually also found in the documentation (http://docs.django-blog-zinnia.com/en/latest/how-to/extending_entry_model.html).
But now i get an error like this:
Unhandled exception in thread started by <function wrapper at 0x1082ad9b0>
Traceback (most recent call last):
File "/myproject/venv/lib/python2.7/site-packages/django/utils/autoreload.py", line 93, in wrapper
fn(*args, **kwargs)
File "/myproject/venv/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 101, in inner_run
self.validate(display_num_errors=True)
File "/myproject/venv/lib/python2.7/site-packages/django/core/management/base.py", line 310, in validate
num_errors = get_validation_errors(s, app)
File "/myproject/venv/lib/python2.7/site-packages/django/core/management/validation.py", line 34, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/myproject/venv/lib/python2.7/site-packages/django/db/models/loading.py", line 196, in get_app_errors
self._populate()
File "/myproject/venv/lib/python2.7/site-packages/django/db/models/loading.py", line 75, in _populate
self.load_app(app_name, True)
File "/myproject/venv/lib/python2.7/site-packages/django/db/models/loading.py", line 99, in load_app
models = import_module('%s.models' % app_name)
File "/myproject/venv/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/myproject/venv/lib/python2.7/site-packages/zinnia/models/__init__.py", line 4, in <module>
from zinnia.models.entry import Entry
File "/myproject/venv/lib/python2.7/site-packages/zinnia/models/entry.py", line 6, in <module>
class Entry(load_model_class(ENTRY_BASE_MODEL)):
File: "/myproject/venv/lib/python2.7/site-packages/zinnia/models_bases/__init__.py", line 20, in load_model_class
raise ImproperlyConfigured('%s cannot be imported' % model_path)
django.core.exceptions.ImproperlyConfigured: zinnia_extra.models.AssociationBlog cannot be imported
I've searched for several hours now, but i am at the end and don't know how to search for this error type. Can someone provide an tutorial on the current extension workflow or help me with this error?
It seems the problem is the importation of zinnia_extra model.
Could be possible you need to add this line:
from zinnia_extra.models import AssociationBlog
in some file ?
I'm not sure in wich file, but it seems Django can't import your created class.
Maybe you need to add this import to your admin.py or other file where Django uses AssociationBlog
Other idea that comes to my mind is:
Could be that you need to add the zinnia_extra path to Python Path ? Is it in the same path as your project or same path as zinnia app?

How can I identify what package an AttributeError: 'module' is referring to?

I am trying to move a Python pyramid app that I'm writing from one server to another. I checked the code out from source control and ran a python setup.py develop to prepare the environment, but when I try to run pserve development.ini I get the following traceback:
2013-02-27 20:38:20,269 INFO [pyramid_scss][MainThread] adding asset path /home/pgrace/repos/Asterisk-WebApps/Cedar-Root/opt/cedar/cedar/assets/scss
Traceback (most recent call last):
File "/home/pgrace/venvs/pyramid/bin/pserve", line 8, in <module>
load_entry_point('pyramid==1.4', 'console_scripts', 'pserve')()
File "/home/pgrace/venvs/pyramid/lib/python2.6/site-packages/pyramid/scripts/pserve.py", line 50, in main
return command.run()
File "/home/pgrace/venvs/pyramid/lib/python2.6/site-packages/pyramid/scripts/pserve.py", line 304, in run
global_conf=vars)
File "/home/pgrace/venvs/pyramid/lib/python2.6/site-packages/pyramid/scripts/pserve.py", line 328, in loadapp
return loadapp(app_spec, name=name, relative_to=relative_to, **kw)
File "/home/pgrace/venvs/pyramid/lib/python2.6/site-packages/paste/deploy/loadwsgi.py", line 247, in loadapp
return loadobj(APP, uri, name=name, **kw)
File "/home/pgrace/venvs/pyramid/lib/python2.6/site-packages/paste/deploy/loadwsgi.py", line 272, in loadobj
return context.create()
File "/home/pgrace/venvs/pyramid/lib/python2.6/site-packages/paste/deploy/loadwsgi.py", line 710, in create
return self.object_type.invoke(self)
File "/home/pgrace/venvs/pyramid/lib/python2.6/site-packages/paste/deploy/loadwsgi.py", line 146, in invoke
return fix_call(context.object, context.global_conf, **context.local_conf)
File "/home/pgrace/venvs/pyramid/lib/python2.6/site-packages/paste/deploy/util.py", line 56, in fix_call
val = callable(*args, **kw)
File "/home/pgrace/repos/Asterisk-WebApps/Cedar-Root/opt/cedar/cedar/__init__.py", line 18, in main
config.include("pyramid_scss")
File "/home/pgrace/venvs/pyramid/lib/python2.6/site-packages/pyramid/config/__init__.py", line 773, in include
c(configurator)
File "/home/pgrace/venvs/pyramid/lib/python2.6/site-packages/pyramid_scss/__init__.py", line 88, in includeme
scss.LOAD_PATHS = ','.join([scss.LOAD_PATHS, ','.join(load_paths)])
AttributeError: 'module' object has no attribute 'LOAD_PATHS'
Now, I can tell that the problem originates in pyramid_scss, but as far as I can tell the code it references is fine, it's as if the module class does not contain the LOAD_PATHS directive. I'm trying to figure out which module it's referring to so that I can track down if I'm missing a dependency or something. Does anyone have any ideas how I'd go about identifying where the module reference is pointing to so I can check that code?
EDIT:
The error comes in the includeme definition which from what I've read is automatically included every time a pyramid-specific package is ...instantiated? Maybe? At any rate, it's saying that scss.LOAD_PATHS does not exist, yes, but there's no scss class in either pyramid_scss or pyScss packages, leading me to wonder if there's some other class that's being late-bound or something.
def includeme(config):
load_paths, static_path = _get_import_paths(config.registry.settings)
scss.LOAD_PATHS = ','.join([scss.LOAD_PATHS, ','.join(load_paths)])
scss.STATIC_ROOT = static_path
config.add_renderer('scss', renderer_factory)
The Scss class in pyScss does include a LOAD_PATHS directive but I don't see where the object scss is bound to a Scss class definition. I'm wondering whether there's something missing in the def includeme from above that might be part of the answer, but then it begs the question -- this worked right on the other machine, why break now? There's something else missing that I'm just not picking up on.
From examining the code for the scss package, it looks like the LOAD_PATHS global variable might have been moved from __init__.py to config.py.
Thus, if you want to try to fix the pyramid_scss app, you could change line 88 of pyramid_scss/__init__.py to read:
scss.config.LOAD_PATHS = ','.join([scss.config.LOAD_PATHS, ','.join(load_paths)])
The one-but-last line tells you which module is affected:
scss.LOAD_PATHS = ','.join([scss.LOAD_PATHS, ','.join(load_paths)])
AttributeError: 'module' object has no attribute 'LOAD_PATHS'
So the scss module has no LOAD_PATHS attribute.

Categories