Django Migrations Circular Dependencies - python

so my django project was working completely fine and everything worked.
I wanted to rename an app something else so I did and updated all the associated files in including the app.py config file.
I also cleared the database and removed all migration files from each app.
Ever since then I have never been able to finish makemigrations onto my apps.
I even recreated the app I renamed, by doing django-admin startapp "appname" and then copied the contents of models.py admin.py, etc over to see if I somehow cause an internal issue but I just can't figure out what's going on?.
I did manage to get all the makemigrations to success for all apps including the one I remade when I removed this (below) from another apps admin.py file
# accounts/admin.py
class SigBotSettingsInLine(admin.StackedInline):
model = SigBotSettings
#admin.register(Bot)
class BotAdmin(admin.ModelAdmin,):
...
inlines = [SigBotSettingsInLine]
but in the end the python manage.py migrate, still Failed. If someone would help it would be highly appreciated.
Here is the error-code:
(dguacENV) PS C:\Users\Admin\Desktop\djangoProjects\dguac> python manage.py makemigrations accounts
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\core\management\commands\makemigrations.py", line 88, in handle
loader = MigrationLoader(None, ignore_no_migrations=True)
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\db\migrations\loader.py", line 53, in __init__
self.build_graph()
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\db\migrations\loader.py", line 286, in build_graph
self.graph.ensure_not_cyclic()
File "C:\Users\Admin\anaconda3\envs\dguacENV\lib\site-packages\django\db\migrations\graph.py", line 274, in ensure_not_cyclic
raise CircularDependencyError(", ".join("%s.%s" % n for n in cycle))
django.db.migrations.exceptions.CircularDependencyError: accounts.0001_initial, accounts.0002_auto_20210809_1814, signals.0001_initial
Dependencies in accounts/migrations/0001_initial.py
dependencies = [
('signals', '__first__'),
('auth', '0012_alter_user_first_name_max_length'),
]
Dependencies in accounts/migraitons/0002_auto_20210809_1910.py
dependencies = [
('accounts', '0001_initial'),
]
Dependencies in signals/migrations/0001_initial.py
dependencies = [
('accounts', '0002_auto_20210809_1910'),
]

Dependencies in accounts/migrations/0001_initial.py
dependencies = [
('signals', '__first__'),
('auth', '0012_alter_user_first_name_max_length'),
]
Dependencies in accounts/migraitons/0002_auto_20210809_1910.py
dependencies = [
('accounts', '0001_initial'),
]
Dependencies in signals/migrations/0001_initial.py
dependencies = [
('accounts', '0002_auto_20210809_1910'),
]
This tells us the following:
accounts.0001.initial depends on signals.0001_initial (specified by '__first__'.
accounts.0002_auto_20210809_1910 depends on accounts.0001.initial
signals.0001_initial.py depends on accounts.0002_auto_20210809_1910
The circularity should be clear.
You can either edit these dependencies manually or delete all migrations and generate them again with ./manage.py makemigrations This should solve the problem unless there are underlying issues with the model dependencies themselves.
WARNING
Be very careful when editing or deleting migrations. If your project is deployed to a live server, editing migrations that have already applied will at best do nothing and at worst completely wreck your production database. The proceeding suggestion should only be used if you are working on a project that has not yet been deployed.

SOLVED:
So yes thank you a lot for pointing out about the migration dependency issue, reading that link made me clearly understand how the makemigrations function works.
So after I looked through my dependencies, I found that in my Signals.models file there was a foriegnkey that linked to the Signals app before it was migrated.
I commented out this foreignkey line then migrated and everything worked perfectly.
I even added the foreignkey back afterwards and updated the migration which also worked because at this point the signal database had already been migrated.
I know this is bad practice though and will he changing the way that foreignkey is linked through another method.
Appreciate the help.

Related

Why is Django unable to run properly?

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

Django "ValueErrror: could not find common ancestor of {migrations}"

I'm trying to follow the documentation in https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/operations/ to create a migration which will essentially perform the SQL statement CREATE EXTENSION IF NOT EXISTS hstore; on the database. I've tried adding the following file, called create_extension_hstore.py, to the migrations directory:
from django.db import migrations
from django.contrib.postgres.operations import CreateExtension
class Migration(migrations.Migration):
operations = [CreateExtension(name='hstore')]
My 'mental model' of this is that since Django infer the order of the migrations from their dependencies and this one has none, it should be run first. However, I'm getting the error when I try to run python manage.py makemigrations --merge:
(venv) Kurts-MacBook-Pro:lucy-web kurtpeek$ python manage.py makemigrations --merge
(0.000) SELECT typarray FROM pg_type WHERE typname = 'citext'; args=None
(0.003)
SELECT c.relname, c.relkind
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r', 'v')
AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
AND pg_catalog.pg_table_is_visible(c.oid); args=None
(0.001) SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"; args=()
Traceback (most recent call last):
File "manage.py", line 29, in <module>
execute_from_command_line(sys.argv)
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 142, in handle
return self.handle_merge(loader, conflicts)
File "/Users/kurtpeek/Documents/Dev/lucy/lucy-web/venv/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 272, in handle_merge
raise ValueError("Could not find common ancestor of %s" % migration_names)
ValueError: Could not find common ancestor of {'0091_family_adopting_or_surrogate', 'create_extension_hstore'}
How can I fix this? I could try adding dependencies=['0001_initial'] to the Migration class but this seems a bit arbitrary as what I actually want is to run this migration before anything else.
I think you would want to add this migration to the dependencies in 0001, if you want it run before the first generated migrations.
If you are just getting to needing hstore now and don't need it to run first you can pretty easily just add as a data migration in place like normal.
I ended up solving the larger problem, using the HStoreField without having to manually run CREATE EXTENSION hstore; on the database, by adding the HStoreExtension() operation to the operations of the 0001_initial.py migration; see also https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/operations/#create-postgresql-extensions.

ImportError: cannot import name widgets from django.contrib.admin

I'm getting the following inexplicable error all of a sudden:
Django Version: 1.4.5
Python Version: 2.7.3
Traceback:
File "/home/webapp/.local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
101. request.path_info)
File "/home/webapp/.local/lib/python2.7/site-packages/newrelic-2.18.1.15/newrelic/hooks/framework_django.py" in wrapper
518. return wrapped(*args, **kwargs)
File "/home/webapp/.local/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
298. for pattern in self.url_patterns:
File "/home/webapp/.local/lib/python2.7/site-packages/django/core/urlresolvers.py" in url_patterns
328. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/webapp/.local/lib/python2.7/site-packages/django/core/urlresolvers.py" in urlconf_module
323. self._urlconf_module = import_module(self.urlconf_name)
File "/home/webapp/.local/lib/python2.7/site-packages/django/utils/importlib.py" in import_module
35. __import__(name)
File "/home/webapp/myApp/cmap/urls.py" in <module>
8. from django.contrib import admin
File "/home/webapp/.local/lib/python2.7/site-packages/django/contrib/admin/__init__.py" in <module>
4. from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
File "/home/webapp/.local/lib/python2.7/site-packages/django/contrib/admin/options.py" in <module>
8. from django.contrib.admin import widgets, helpers
Exception Type: ImportError at /
Exception Value: cannot import name widgets
I can successfully import widgets (from django.contrib.admin import widgets) using the Django shell and a python shell, but it doesn't work when I run my web app.
The command I'm using to launch the app is:
newrelic-admin run-program python manage.py run_gunicorn ...
I have gone back through my recent commits and don't see anything that could be related to this error.
Without knowing what is actually in your app, it's difficult to say for certain what happened. However, in the past, when I have encountered similar ImportErrors, the most common causes were:
Circular imports (a imports b, b imports c, ..., z imports a)
Couldn't find module (improperly set up PYTHONPATH)
Missing dependency (forgot to pip install ...)
I see the following line in the traceback -
File "/home/webapp/myApp/cmap/urls.py" in <module>
8. from django.contrib import admin
File "/home/webapp/.local/lib/python2.7/site-packages/django/contrib/admin/__init__.py" in <module>
Seems like a circular import issue , do you really need that import in that file?
I finally tracked this down to the commit that caused the problem. I had added this to my logging configuration in settings.py:
'loggers' : {
'': {
'level': 'DEBUG',
'handlers': ['logfile','sentry'],
'propagate': False,
...thinking that I was adding a default logger. This led to a string of inexplicable errors, including the one I posted here. Removing it fixed everything.
Note that Ming's answer is the best general purpose answer to this error.

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.

Django wsgi.py change monitor detecting changes when none have been made

I'm developing django based site on a windows machine, but I git push my changes to a headless Ubuntu server for staging purposes. When I git pull the changes into the working directory on the staging server I then need to run manage.py collectstatic. However, when I do this the change monitor ('Monitoring Code Changes' section of Reloading Source Code) reports that it has detected changed files:
monitor (pid=26216): Starting change monitor.
You have requested to collect static files at the destination
location as specified in your settings.
This will overwrite existing files!
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: monitor (pid=26216): Change detected to 'myproject/manage.py'.
monitor (pid=26216): Triggering process restart.
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/envs/myproject/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 453, in execute_from_command_line
utility.execute()
File "/envs/myproject/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/envs/myproject/local/lib/python2.7/site-packages/django/core/management/base.py", line 222, in run_from_argv
self.execute(*args, **options.__dict__)
File "/envs/myproject/local/lib/python2.7/site-packages/django/core/management/base.py", line 255, in execute
output = self.handle(*args, **options)
File "/envs/myproject/local/lib/python2.7/site-packages/django/core/management/base.py", line 385, in handle
return self.handle_noargs(**options)
File "/envs/myproject/local/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 160, in handle_noargs
% (destination_display, clear_display))
KeyboardInterrupt
I ran 'touch myproject/wsgi.py' to 'update the change cache' and then ran the collectstatic command again. This resulted in the same error.
I then entered the python console and ran the monitor starting command manually:
import myproject.monitor
myproject.monitor.start(1)
This made no difference. I also tried adding a conditional to the monitor so that it would ignore manage.py when checking for file changes but this just gave me the same error with myproject/__init__.py being the file it reported as having changed. DOes anyone know what is causing this?
I've worked out what was causing this. The legacy file modification times are held in a dictionary as unix timestamps with decimal places (e.g. 1366283624.92) while the actual modification times are returned by os.stat(path).st_mtime as integers. All I had to do was edit the monitor script at line 54, changing:
if mtime != _times[path]:
to
if int(mtime) != int(_times[path]):
I just hope this doesn't lead to any further problems down the road

Categories