How Django skipping an app when using syncdb command - django

I have a Django project which has two apps (one created as debug test). For the debug test, syncdb does put the model in the database but for the other it does not.
Both are in settings.INSTALLED_APPS.
There are around seven models, none of them being recognized.
Neither the server, any page or the syncdb-console give any errors.
Models are in a models directory. As a test, there is also one in app/models.py (doesn't work either).
Most strikingly to me is that the below code does display the models which aren't synced (executed from the app that is skipped):
for model in get_models():
models.append(model)
pass models to a template
Any help would be much appreciated. I think it is something trivial but I'm out of ideas for things to try.
Thanks,
UPDATE:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.admin',
'techtree',
'froink',
)
Structure:
project/techtree/models.py (contains a test model)
project/techtree/models/__init__.py (as described here)
project/techtree/models/typ.py (contains model Type)
There are more files of the same type as the last line.

Are you missing the __init__.py file in the second app's models directory? That would mean it can't be found on the path.
Can you show us your INSTALLED_APPS setting, and your directory structure please?
Looking at your directory structure, I think I can guess what's wrong.
my_app/
__init__.py
my_module.py
my_module/
__init__.py
my_python_file.py
With the above fictional directory structure, what gets imported when I do the following?
from my_module import *
Does that import everything from within my_module.py or everything within the my_module directory?
Use one, or the other. Not both. Put everything inside your models.py file, and get rid of the directory unless you have a good reason for having a models directory. You probably don't.

I faced this same problem, It took hours for me to figure out how to group models in to a separate directory. Heres how to do it,
Add a meta class to each of your models with an app_label parameter.
from django.db import models
class Test(models.Model):
class Meta:
app_label = 'myapp'
Here's where I found out about this,
Placing Django Models In Separate Files
But doing this wasn't enough you have to import the models in an __init__.py file in the models directory like this,
from YourModelFile import *

Django is usually searching for a models.py file only. If you have models.py and a module sub directory called models with an __init__.py file it is not recognizing the models correctly (my guess). You can do one of these two:
Remove your sub-module completely and keep all your model definitions in models.py
OR
Remove models.py in techtree. Add a models.py file to your techtree.models app where you keep the model definitions. Add 'techtree.models' to your INSTALLED_APPS (just 'techtree' is no enough).
Hope one of these answers helps.

Check the file name is
__init__.py
and not
init.py

Related

django makemigrations doesn't recognize new model [duplicate]

I was trying to create migrations within an existing app using the makemigrations command but it outputs "No changes detected".
Usually I create new apps using the startapp command but did not use it for this app when I created it.
After debugging, I found that it is not creating migration because the migrations package/folder is missing from an app.
Would it be better if it creates the folder if it is not there or am I missing something?
To create initial migrations for an app, run makemigrations and specify the app name. The migrations folder will be created.
./manage.py makemigrations <myapp>
Your app must be included in INSTALLED_APPS first (inside settings.py).
My problem (and so solution) was yet different from those described above.
I wasn't using models.py file, but created a models directory and created the my_model.py file there, where I put my model. Django couldn't find my model so it wrote that there are no migrations to apply.
My solution was: in the my_app/models/__init__.py file I added this line:
from .my_model import MyModel
There are multiple possible reasons for django not detecting what to migrate during the makemigrations command.
migration folder You need a migrations package in your app.
INSTALLED_APPS You need your app to be specified in the INSTALLED_APPS .dict
Verbosity start by running makemigrations -v 3 for verbosity. This might shed some light on the problem.
Full path In INSTALLED_APPS it is recommended to specify the full module app config path 'apply.apps.MyAppConfig'
--settings you might want to make sure the correct settings file is set: manage.py makemigrations --settings mysite.settings
specify app name explicitly put the app name in manage.py makemigrations myapp - that narrows down the migrations for the app alone and helps you isolate the problem.
model meta check you have the right app_label in your model meta
Debug django debug django core script. makemigrations command is pretty much straight forward. Here's how to do it in pycharm. change your script definition accordingly (ex: makemigrations --traceback myapp)
Multiple databases:
Db Router when working with django db router, the router class (your custom router class) needs to implement the allow_syncdb method.
makemigrations always creates migrations for model changes, but if
allow_migrate() returns False,
I've read many answers to this question often stating to simply run makemigrations in some other ways. But to me, the problem was in the Meta subclass of models.
I have an app config that says label = <app name> (in the apps.py file, beside models.py, views.py etc). If by any chance your meta class doesn't have the same label as the app label (for instance because you are splitting one too big app into multiple ones), no changes are detected (and no helpful error message whatsoever). So in my model class I have now:
class ModelClassName(models.Model):
class Meta:
app_label = '<app name>' # <-- this label was wrong before.
field_name = models.FloatField()
...
Running Django 1.10 here.
Another thing that will cause this is a trailing comma after the field which will cause the field to skipped during makemigrations:
class MyModel(models.Model):
name = models.CharField(max_length=64, null=True) # works
language_code = models.CharField(max_length=2, default='en') # works
is_dumb = models.BooleanField(default=False), # doesn't work
I had a trailing , in one line perhaps from copy&paste. The line with is_dumb doesn't create a model migration with ./manage.py makemigrations because Python thinks it is a tuple, and Django doesn't consider it a field.
It is a comment but should probably be an answer.
Make sure that your app name is in settings.py INSTALLED_APPS otherwise no matter what you do it will not run the migrations.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
]
Then run:
./manage.py makemigrations blog
update: One should make sure that an __init__.py file exists in the migrations folder before trying:
./manage.py makemigrations <myapp1> <myapp2> ... <myappN>
There are sometimes when ./manage.py makemigrations is superior to ./manage.py makemigrations <myapp> because it can handle certain conflicts between apps.
Those occasions occur silently and it takes several hours of swearing to understand the real meaning of the dreaded No changes detected message.
Therefore, it is a far better choice to make use of the following command:
./manage.py makemigrations <myapp1> <myapp2> ... <myappN>
Method : 1
Step : 1
Make sure your app must be included in INSTALLED_APPS in settings.py
Stpe : 2
python manage.py makemigrations <appname>
if same message shows (No changes detected)
!Warning This is Very Risky For Your Project So Make Sure You Have Backup For Your Project Before Applying The Method 2.
Method 2
rename your app name and make new app using :
django-admin startapp <appname>
copy all .py files except from the old app
migration folder
pycache folder
init.py
test.py file if you didn't wrote code in it
and paste into the new app which you made recently
remember you have to make exact the same name for new app otherwise you have to make more changes in the project.
Make sure your app is mentioned in installed_apps in settings.py
Make sure you model class extends models.Model
My problem was much simpler than the above answers and probably a far more common reason as long as your project is already set up and working. In one of my applications that had been working for a long time, migrations seemed wonky, so in a hurry, I did the following:
rm -r */migrations/*
rm db.sqlite3
python3 manage.py makemigrations
No changes detected
Whaat??
I had mistakenly also removed all the __init__.py files :( - Everything was working again after I went in and:
touch ads1/migrations/__init__.py
For each of my applications then the makemigrations worked again.
It turns out that I had manually created a new application by copying another and forgot to put the __init__.py in the migrations folder and that confinved me that everything was wonky - leading my making it worse with an rm -r as described above.
Hope this helps someone from swearing at the "No changes detected" error for a few hours.
I had copied a table in from outside of django and the Meta class defaulted to "managed = false". For example:
class Rssemailsubscription(models.Model):
id = models.CharField(primary_key=True, max_length=36)
...
area = models.FloatField('Area (Sq. KM)', null=True)
class Meta:
managed = False
db_table = 'RSSEmailSubscription'
By changing managed to True, makemigrations started picking up changes.
Another possible reason is if you had some models defined in another file (not in a package) and haven't referenced that anywhere else.
For me, simply adding from .graph_model import * to admin.py (where graph_model.py was the new file) fixed the problem.
When adding new models to the django api application and running the python manage.py makemigrations the tool did not detect any new models.
The strange thing was that the old models did got picked by makemigrations, but this was because they were referenced in the urlpatterns chain and the tool somehow detected them. So keep an eye on that behavior.
The problem was because the directory structure corresponding to the models package had subpackages and all the __init__.py files were empty. They must explicitly import all the required classes in each subfolder and in the models __init__.py for Django to pick them up with the makemigrations tool.
models
├── __init__.py <--- empty
├── patient
│ ├── __init__.py <--- empty
│ ├── breed.py
│ └── ...
├── timeline
│ ├── __init__.py <-- empty
│ ├── event.py
│ └── ...
This might hopefully help someone else, as I ended up spending hours trying to chase this down.
If you have a function within your model by the same name, this will remove the value. Pretty obvious in hindsight, but nonetheless.
So, if you have something like this:
class Foobar(models.Model):
[...]
something = models.BooleanField(default=False)
[...]
def something(self):
return [some logic]
In that case, the function will override the setting above, making it "invisible" to makemigrations.
A very dumb issue you can have as well is to define two class Meta in your model. In that case, any change to the first one won't be applied when running makemigrations.
class Product(models.Model):
somefield = models.CharField(max_length=255)
someotherfield = models.CharField(max_length=255)
class Meta:
indexes = [models.Index(fields=["somefield"], name="somefield_idx")]
def somefunc(self):
pass
# Many lines...
class Meta:
indexes = [models.Index(fields=["someotherfield"], name="someotherfield_idx")]
In my case i forgot to insert the class arguments
Wrong:
class AccountInformation():
Correct
class AccountInformation(models.Model):
I had a different issue while creating a new app called deals. I wanted to separate the models inside that app so I had 2 model files named deals.py and dealers.py.
When running python manage.py makemigrations I got: No changes detected.
I went ahead and inside the __init__.py which lives on the same directory where my model files lived (deals and dealer) I did
from .deals import *
from .dealers import *
And then the makemigrations command worked.
Turns out that if you are not importing the models anywhere OR your models file name isn't models.py then the models wont be detected.
Another issue that happened to me is the way I wrote the app in settings.py:
I had:
apps.deals
It should've been including the root project folder:
cars.apps.deals
I solved that problem by doing this:
Erase the "db.sqlite3" file. The issue here is that your current data base will be erased, so you will have to remake it again.
Inside the migrations folder of your edited app, erase the last updated file. Remember that the first created file is: "0001_initial.py". For example: I made a new class and register it by the "makemigrations" and "migrate" procedure, now a new file called "0002_auto_etc.py" was created; erase it.
Go to the "pycache" folder (inside the migrations folder) and erase the file "0002_auto_etc.pyc".
Finally, go to the console and use "python manage.py makemigrations" and "python manage.py migrate".
I know this is an old question but I fought with this same issue all day and my solution was a simple one.
I had my directory structure something along the lines of...
apps/
app/
__init__.py
app_sub1/
__init__.py
models.py
app_sub2/
__init__.py
models.py
app_sub3/
__init__.py
models.py
app2/
__init__.py
app2_sub1/
__init__.py
models.py
app2_sub2/
__init__.py
models.py
app2_sub3/
__init__.py
models.py
main_app/
__init__.py
models.py
And since all the other models up until the one I had a problem with were being imported somewhere else that ended up importing from main_app which was registered in the INSTALLED_APPS, I just got lucky that they all worked.
But since I only added each app to INSTALLED_APPS and not the app_sub* when I finally added a new models file that wasn't imported ANYWHERE else, Django totally ignored it.
My fix was adding a models.py file to the base directory of each app like this...
apps/
app/
__init__.py
models.py <<<<<<<<<<--------------------------
app_sub1/
__init__.py
models.py
app_sub2/
__init__.py
models.py
app_sub3/
__init__.py
models.py
app2/
__init__.py
models.py <<<<<<<<<<--------------------------
app2_sub1/
__init__.py
models.py
app2_sub2/
__init__.py
models.py
app2_sub3/
__init__.py
models.py
main_app/
__init__.py
models.py
and then add from apps.app.app_sub1 import * and so on to each of the app level models.py files.
Bleh... this took me SO long to figure out and I couldn't find the solution anywhere... I even went to page 2 of the google results.
Hope this helps someone!
I forgot to put correct arguments:
class LineInOffice(models.Model): # here
addressOfOffice = models.CharField("Корхоная жош",max_length= 200) #and here
...
in models.py
and then it started to drop that annoying
No changes detected in app 'myApp '
INSTALLED_APPS = [
'blog.apps.BlogConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
make sure 'blog.apps.BlogConfig', (this is included in your settings.py in order to make your app migrations)
then run python3 manage.py makemigrations blog or your app name
This could be done by using two steps that are mentioned below.
add your app to settings.py > INSTALLED_APPS
open admin.py
from .models import upImg
# Register your models here.
admin.site.register(upImg)
NOTE: replace upImg with your className defined in models.py
after that see if there still any python manage.py makemigrations are left or not. if there is, than execute python manage.py migrate too.
For more info follow this django tutorial.
The solution is you have to include your app in INSTALLED_APPS.
I missed it and I found this same issue.
after specifying my app name migration became successful
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'boards',
]
please note I mentioned boards in last, which is my app name.
One more edge case and solution:
I added a boolean field, and at the same time added an #property referencing it, with the same name (doh). Commented the property and migration sees and adds the new field. Renamed the property and all is good.
Try registering your model in admin.py, here's an example:-
admin.site.register(YourModelHere)
You can do the following things:-
1. admin.site.register(YourModelHere) # In admin.py
2. Reload the page and try again
3. Hit CTRL-S and save
4. There might be an error, specially check models.py and admin.py
5. Or, at the end of it all just restart the server
I had a similar issue with django 3.0, according migrations section in the official documentation, running this was enough to update my table structure:
python manage.py makemigrations
python manage.py migrate
But the output was always the same: 'no change detected' about my models after I executed 'makemigrations' script.
I had a syntax error on models.py at the model I wanted to update on db:
field_model : models.CharField(max_length=255, ...)
instead of:
field_model = models.CharField(max_length=255, ...)
Solving this stupid mistake, with those command the migration was done without problems. Maybe this helps someone.
My problem with this error, was that I had included:
class Meta:
abstract = True
Inside model that I wanted to creation migrate for.
Its easy, you need to add empty init.py in empty migrations folder.
Then check migrations using "python manage.py makemigrations"
Directory structure-
Your App
migrations
init.py
You should add polls.apps.PollsConfig to INSTALLED_APPS in setting.py
The possible reason could be deletion of the existing db file and migrations folder
you can use python manage.py makemigrations <app_name> this should work. I once faced a similar problem.

Dotted name in AppConfig

With django 1.7 they added support for configuration classes instead of the magic string from previous versions.
My project has several applications into a folder named apps which is added to the PYTHON_PATH.
After adding a simple AppConfig derived class I'm running into many import errors and I want to rule out silly mistakes.
Suppose this structure:
project_root/
my_project/
apps/
my_app/
another_app/
Would it be correct to have this config?:
# my_app/apps.py
class MyAppConfig(AppConfig):
name = 'apps.my_app'
# my_app/__init__.py
default_app_config='apps.my_app.apps.MyAppConfig'
# settings.py
INSTALLED_APPS = (
...
'apps.myapp.apps.MyAppConfig'
...
)
Curently the project fails when trying to import models (or tasks or any other module) issuing:
from apps.my_app.tasks import AwesomeTask
ImportError: no module named my_app.tasks
I solved a similar issue by renaming the apps folder. It was somehow conflicting with Django internals system.
I hope this helps someone.

Django 1.5.1 - Admin.py missing while running startapp

I've been following the DjangoProject tutorial. When I run python manage.py startapp newapp while in the same directory as manage.py. In the newapp directory I see init.py, models.py, tests.py, and views.py but not admin.py file. Where is admin.py?
I am running Django 1.5.1 in Windows 8
You have to create an admin.py file.
you don't necessarily need an admin.py file,
just import the admin module in your models.py file,
from django.contrib import admin
and for each model do the following:
admin.site.register(model1)
admin.site.register(model2)
However, this is not best practice, but since it's just a tutorial, it will work.
You also need to uncoment the relevant lines in the urls.py file
I think I had the same frustrations following the DjangoProject tutorial - however, when I cross-referenced it with with the DjangoBook tutorial (for the same version, I believe, 1.5.1), I found that an admin.py file was not necessarily created after a python manage.py startapp xyz command -- moreover, I also uncommented all of the admin options in urls.py, views.py, and settings.py - so a bit of a mix of what Neal and Ibrahim said
You have to create your own admin.py file in the app if you want it. Indeed, this file is optionnal and isn't created by startapp.
If you want a default template to begin your admin.py, it should be:
from django.contrib import admin
from models import Model1, Model2
class Model2Admin(admin.ModelAdmin):
list_display = ('title', 'content', 'date')
# Just an example, chekc docs and tutorials for more info.
admin.site.register(Model1)
admin.site.register(Model2, Model2Admin)
The reason there is no default admin.py is because you don't have any models yet when you create your new application; so there is nothing to add to the admin section.
Further, you may not want to admin all the models in your application; or you may be creating an application that does not need any admin hookups; or you may not be using the admin application at all in your project.
Since django cannot decide this for you, there is no default admin.py generated.
To create one, if you are following the tutorial - simply keep reading and in part two you'll create the admin.py file when you learn about the admin contrib app and how to integrate it with your custom models.

django inspectdb in admin site (admin.site.register)

I have been given a small legacy db (mysql) to work with, and therefore, I have tried to use the inspectdb command in django.
So, I use something like:
python manage.py inspectdb > models.py
It works fine, and I take the models.py and copy the class it created into my app (searchapp) as a models.py file.
I have done a syncdb, and everything went fine. Results are as expected.
Now, I have tried to add this model into my admin site, using:
from searchapp.models import Abaqus
from django.contrib import admin
admin.site.register(Abaqus)
stored in a file called admin.py (Abaqus is the name of the class generated by inspectdb and searchapp is the app name). However, I am not able to see the app on the admin site. I have checked my settings.py and it includes the 'searchapp'.
I was wondering if someone could point me in the right direction..
I suspect admin.py is not loaded. You could check this by putting a debug statement just above the register call:
import pdb;pdb.set_trace()
admin.site.register(Abaqus)
If this is in fact the case, the correct way to ensure admin.py is loaded is to call django.contrib.admin.autodiscover() at the beginning of your main url conf.
If you've written no admin classes and don't want an admin.py, you can call admin.site.register(Abaqus) right below where the model is defined, inside models.py.
If you have an admin module structured like the following, import admin within models.py to ensure the code is run:
myapp
|--models.py
|--views.py
|--admin
|--__init__.py
|--views.py
|--base.py
Another possible cause would be that you are missing the permissions to edit the model. Double check that you are logged in as a superuser.

Problem loading custom template tags (Error: No module named x)

I am currently writing a few custom template tags but for some reason they will not load. My directory structure is as follows:
MyProj
|
----MyApp
|
|----templatetags
|
|----myapp_tags.py
|----__init__.py
In myapp_tags.py
from django.template import Library, Node
from myproj.myapp.models import Product
register = Library()
class LatestProductsNode(Node):
def render(self, context):
context['recent_products'] = Product.objects.all()[:5]
return ''
def get_latest_products(parser, token):
return LatestProductsNode()
get_latest_products = register.tag(get_latest_products)
In settings.py
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'myproj.myapp',
)
In the Template
{% load myapp_tags %}
The error i get when trying to load the page:
Exception Type: TemplateSyntaxError Exception Value:
'myapp_tags' is not a valid tag library: Could not load template library from django.templatetags.myapp_tags, No module named myapp_tags
in settings.py, you should never name the project 'myproj' explicitely. In INSTALLED_APPS, just use 'myapp'. Also, you should have this :
TEMPLATE_LOADERS = (
'django.template.loaders.app_directories.load_template_source',
)
And be sure to have an __init__.py in the myapp folder as well as in templatetags.
Use manage.py shell then from myapp.templatetags import myapp_tags to find out if theres any python error in the myapp_tags.py file.
Also, be sure that myapp_tags.py file name doesnt conflicts with another folder/file in your project.
Hope this helps.
One thing that's tripped me up is that the magic importing of templatetags bypasses the automatic reloading of the development server.
If the following works in manage.py shell
>>> from django.templatetags import myapp_tags
>>>
Then everything is actually working and you just need to reload the development server. If on the other hand you get an ImportError then something is wrong and you should check your INSTALLED_APPS, that you have an __init__.py file in the templatetags directory and all the other things suggested in the other answers.
This will probably only apply to a tiny fraction of the people who experience template tag loading problems, but this is the second time I've arrived at this question in as many weeks and both times it's just taken restarting the development server to get things working.
Some reasons:
due to error in templatetgs code.
If you have used model import in templatetags
For #2, for example. If you are doing:
from your_app2.models import model
This will go wrong, so instead above, you should do
from your_project.your_app2.models import model
It worked me this way.
I just came across the same problem in Django 2 and realized that the custom template tag files must have unique names across all of your project apps.
The problem is that nyapp_tags is not at the top level of an installed project. If you put myproj.myapp.templatetags in INSTALLED_APPS, you should be fine.