Django test not running specific app tests - django

I have an app named "sites" that runs normally through the built in server and I can interact with it without any issues.
I added tests in the standard tests.py file and ran "manage.py test sites"
I have two tests in my tests.py file all starting with "test".
When I run the manage.py command in verbose mode, I get:
test_get_current_site (django-contrib.sites.tests.SitesFrameworkTests) ... ok
test_save_another (django-contrib.sites.tests.SitesFrameworkTests) ... ok
etc.
It looks to me that I have a name conflict with an internal module.
Is there any way I can get manage.py to test my code or should I just bite the bullet and change my app name?

Rename your app. From the docs on the INSTALLED_APPS setting:
App names must be unique
The application names (that is, the final dotted part of the path to the module containing models.py) defined in INSTALLED_APPS must be unique. For example, you can’t include both django.contrib.auth and myproject.auth in INSTALLED_APPS.
In this case, your sites app clashes with the Django sites framework, django.contrib.sites.

Related

Do you think this is the right way to rename a django app?

I read different threads and tutorials on renaming and migrating a Django app (How to rename a Django app and migrate data from an app to the other for instance), I also tried to use the django package called django-rename-app but it didn't work at all.
I'm going to explain the way I renamed my app in my development environment and I would like to know if you expect troubles, as apparently everything is working just as it did before so I'm considering doing the same in production.
Here are the steps I took inside my root project directory and my virtualenv activated, using Django 3.2:
Create the destination app
django-admin startapp app2
Copy these files and directories
cp app1/*.py app2/
mkdir app2/templates
mkdir app2/static
cp app1/templates app2/templates
in this case I had a sub-folder named after the app so I renamed it like this
mv app2/templates/app1 app2/templates/app2
cp app1/static app2/static
Models.py
Change the related_name attributes of all ForeignKeys in my new models.py and update all their references inside my views, admin, form and templates
Make sure your apps won't imported by the same name
Look for the instanciation of an AppConfig class inside your app directory and if you find something like this:
from django.apps import AppConfig
class AnunciosConfig(AppConfig):
name = 'app1'
that's where you need to also change your app name from app1 to app2
Activate the new app
Add my app2 to the list of the enabled apps of settings.py
Delete __pycache__
Find and delete or empty all the __pycache__ directories in app2
Migrations
this will not work until all the overlapping bits are corrected, so this is how I tested everything was ok (it will not be aware of URLs problem at this stage)
python manage.py makemigrations
python manage.py migrate
Cloning data
Now I used the Django shell to migrate data from app1 to the app2
python manage.py shell
import app1
from app2.models import *
So I will have to use "app1.ModelName" to refer to the old app and simply "ModelName" to address the new app2 instances
Then I use the Models and QuerySet API to just create new objects in app2 with for loops for each app1 instances, with a corresponding app2 object that is saved (this needs be written individually and depends on each situation)
Deactivate the old app
Now I remove or comment out the old app1 reference in settings.py so that it is disabled
Rename the directory
At this point I needed to rename the app1/ directory to something unknown to Django
mv app1 app1_
Deal with the new errors
It seems some more errors appeared here with URLS and Views, so I had to just update app1 references to app2 until they disappeared
Delete Database table
Enter MySQL (in my case), and disable FOREIGN_KEY_CHECKS
USE yourowndjangodatabase;
SHOW TABLES;
SET FOREIGN_KEY_CHECKS=0;
so now I can delete them like this
DROP TABLE app1__yourfirstmodel;
DROP TABLE app1__yoursecondmodel;
and so on until none is left, then set the FOREIGN_KEY_CHECKS back to 1 so that it is enabled
SET FOREIGN_KEY_CHECKS=1;
Like I saw here Can't drop table: A foreign key constraint fails
CONCLUSION
And basically that was it, it worked perfectly for my development environment. I have a perfect copy of my previous app1 and web application that is just using app2 now.
I improvised so I'm not sure this is the right procedure but it worked so I would like to ask if you see any problem or suspect there will be issues in production.

Django single-test migration

I have recently implemented a reusable app within the django project I am working on. For the sake of the question, let's call it reusable_app. This app also has some unittests that run, however, these tests depend on some basic models declared somewhere next to the tests in a model.py.
/resuable_app
__init__.py
models.py
views.py
urls.py
/tests
__init__.py
tests.py
/simple_app
__init__.py
models.py
Now, the models aren't loaded in the database unless I specify the folder in INSTALLED_APPS in the testing configuration file. I was wondering if there is another way to achieve this, not having to expose the app in the settings file? I seem to be able to specify the app via #override_settings, but the migrations are not ran.
Ex:
#override_settings(INSTALLED_APPS=['reusable_app'])
class TestReusableApp(TestCase):
def test_something(self):
...
If reusable_app is not specified in the settings module INSTALLED_APPS this still yields a ProgrammingError. Am I missing something or is there another approach?
I think the issue here is that the test runner is setting up the tables before you add the app with #override_settings.
Normally what I do with reusable apps is to run the tests in the context of an "example" app, with settings that include the app your want to test. Usually works pretty well, as I'm packaging the reusable app separately. Here's an example of this from a past project of mine.
However, if that's not possible, you might try to override setUp in your tests, and call the "migrate" command within that code. For example:
from django.core.management import call_command
#override_settings(INSTALLED_APPS=['reusable_app'])
MyTestCase(TestCase):
def setUp(self):
call_command('migrate', 'reusable_app')
This is a bit messy, but it might be worth trying. Depending on how things go, you might also have to run django.setup().

PyCharm cannot resolve reference in __init__.py with Django project apps

I am at my wits end with this issue, and would love some help resolving this.
I have a Django project with a bunch of sub apps as such:
my_project/
manage.py
my_project/
settings.py
urls.py
wsgi.py
app_root/
__init__.py
app1/
__init__.py
models.py
views.py
urls.py
templates/
[various templates].html
app2/
__init__.py
models.py
[etc]
app3/
[etc]
in my django settings.py i have installed apps as such:
app_root.app1,
app_root.app2,
In PyCharm, I've tried various things but essentially have Content Root as the top "my_project/" and app_root, app1, app2, etc as Source Roots. I've tried just having app_root as the only Source Root, and I've tried having only app1, app2, etc only as Source Roots, but nothing makes any difference.
Everything functions fine. app runs and everything. However, PyCharm has an inability to resolve my apps.
However, if i try this:
import app_root
...
def some_function(self):
app_root.app1.models.My_Model.objects.all()
it will highlight app1 with the error "Cannot find reference 'app1' in '__init__.py'"
This also means it can't do autocomplete anywhere in the path while doing app_root.app1. - it has no idea about models, views, etc. despite having an (empty) __init__.py in every directory.
I also cannot use any refactoring because it always says "Function is not under the source root"
I've spent countless hours trying to get PyCharm to behave but simply cannot find a way to do it. Is there any way this can be done so PyCharm will autocomplete my apps and not keep giving inspection warnings?
I had some similar issues. My solution; within the PyCharm preferences I added a path to app_root in my active Python Interpreter.
After an exchange with the PyCharm folks, here is what I learned:
Django imports all apps in INSTALLED_APPS variable and their models using __import__ for its own purposes.
In your case, it runs
__import__("app_root.app1")
__import__("app_root.app1.models")
After that, you call import app_root and obtain module app_root with app_root.app1 and app_root.app1.models already imported by internal Django code
Fact that Django imports apps and models is Django internals, it is undocumented and may be changed in future releases. We believe you should not rely on it in your production code, nor PyCharm should.
Here is example in bare python (no django):
__import__("encodings.ascii")
import encodings
print (encodings.ascii.Codec) # this code works, but PyCharm marks "ascii" as "unknown module"
So basically, it's not supposed to work as import app_root, but Django funkiness is masking that.

what magic is "django-admin startapp" doing, that the test runner needs to find my tests.py

I was having a problem that the django test runner wasn't finding the tests for my app, like this one:
Django test runner not finding tests
One of the comments on that thread suggested creating a new app with django-admin.py and seeing if the tests ran there. e.g.
django-admin.py startapp delme
then
adding "delme" to my INSTALLED_APPS
then
copying my tests.py from the app where it wasn't getting found into delme/
and viola! the tests did run. So, OK, I have a work arround, but I don't understand. I re-read what I think should be the relevant parts of the django documentation but the penny refuses to drop.
BTW, the app works via runserver and wsgi, so there doesn't appear to be any gross configuration problem. And my tests all pass from their new home, so I obviously need more tests :)
Specifically, I'm running django in a virtualenv, so I had run "django-admin.py startapp" in the (activated) virtualenv where I wanted the tests to run. This doesn't make the tests run in my other virtualenvs, I still have the old symptoms there (Ran 0 tests). I have a multitude of virtualenvs, managed by non-trivial paver scripts. One uses "path.copytree" for deploying projects, rewrites apache config files, restarts apache, writes wsgi files using the appropriate virtualenv, etc. The other uses PIP/GCC/aptitude/etc for bootstrapping/tearing down the different environments, updating packages as per configuration, etc. So I want to understand the difference between django-startapp and simply copying files, so I can fix these paver scripts so the tests can run in any environment I want them to.
The only thing that makes sense to me, after reading your description, is the location of paths for your existing apps. Can you confirm the following things:
Your app is at the same folder level as the delme app
Your app folder contains an __init__.py file
Your app is listed in the INSTALLED_APPS setting
I'm going to guess that it's a missing __init__.py file, as that trips some people up. To answer your specific question, django-admin startapp doesn't do anything magical. It just creates the right folders and files in the correct place.
Your folder structure should be...
my_project/
__init__.py
manage.py
settings.py
my_app/
__init__.py
tests.py
models.py
delme/
__init__.py
tests.py
models.py
Also note this comment
You can't easily name the TestCase class directly. You name the app, the Django runner does it's discovery thing by looking in models.py and tests.py
solved (still with a little whiff of magic).
diff showed that my old app didn't have a models.py but the new app ("delme", working) did. I didn't think the old app needed one, it was importing all it's domain classes from other places.
Touching an empty models.py in my old app fixed it, now the test runner finds the tests.py and everything works as expected. Condlusion - if an app has no models.py, the django test runner won't find the app's tests.py.
What I said about not working in different virtualenvs was bogus (red herring), I was a bit confused about what my deploy scripts were doing.

Cannot start any django app

I am a newbie at Django and everytime I try to run
python panel/manage.py startapp %app% (panel is my project) it gives me the error:
Error: '%app%' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name.
Am I doing something wrong?
Surely companies or contacts or stats is not the name of an existing Python module?
This is a fun one - your project and your app need to have different names. You probably created a project, then tried to startapp with the same name.
I was confused as well, until I realized that a Django project is a container for applications; this sequence makes it a bit clearer:
# first create a Project (container).
django-admin.py startproject Project
# create multiple apps
cd Project
python manage.py startapp polls
python manage.py startapp hello
...
Perhaps you need to
cd panel
python manage.py startapp yourappname
I'm not sure running the command from a directory above your project will work properly.
I had the same issue because I was trying to "restart" my app after carrying out changes, but startapp is meant to be used once to create a new app. To view changes, syncronize app with DB with python manage.py migrate and restart the server with python manage.py runserver instead.
From the django-admin docs
(manage.py does essentially the same thing as django-admin)
startapp <app_label> [destination]
django-admin startapp
Creates a Django app directory structure for
the given app name in the current directory or the given destination.
By default the directory created contains a models.py file and other
app template files. (See the source for more details.) If only the app
name is given, the app directory will be created in the current
working directory.
If the optional destination is provided, Django will use that existing
directory rather than creating a new one. You can use ‘.’ to denote
the current working directory.
For example:
django-admin startapp myapp /Users/jezdez/Code/myapp
This message is displayed if you run "startapp" twice with the same app name. As pointed out above by the OP it doesn't reload the app, it creates one.
You should choose different names for your project and app in Codes:
django-admin startproject **my_project**
python manage.py startapp **my_app**
You need to create the directory before using the commands. Suppose you want a polls app inside apps folder.
mkdir apps apps/polls
python manage.py startapp polls apps/polls
I guess maybe you have already created the app's dir in panel dir manually. The command 'startapp' is to create an app automatically. If you already have one there, it fails.
I reproduced the issue and there's actually something not working as I expected.
I wonder if we stumbled upon a Django's bug, or a limitation that I don't understand.
Having a project called "project" and an empty folder app/newapp
…I tried:
python manage.py startapp newapp apps/newapp
It returns:
CommandError: 'newapp' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name.
But if I target ANY other route in which the last folder is not called the same name as the app I'm starting, it works.
So I ended up doing:
python manage.py startapp newapp apps/main
Using Django 2.1.3.
if you want to make an empty directory that will contain your new app
project-dir
└── blog
├── __init__.py
├── ...
├── blog-ext #this empty dir that will contain the new app
└── views.py
so instead of typing :
python manage.py newapp blog/blog-ext
it should be :
django-admin startapp newapp blog/blog-ext
Try classic "mysite" or "myproject". You can delete it anytime you want, so if it will accepted, then all your privious ideas conflict with Python modules.
Edit: I tried all your ideas, there was no error for me. So, if you installed support libraries or modules for django, then some of them can contains such names.
this error is because of the name conflicts between the app name and project name.you had given same name for your app and project .your project and app need to be different name .if you had given the same name the above mentioned error will occur .
understand the difference between app and project
Projects vs. apps
What’s the difference between a project and an app? An app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects.
first create the project.
then create the app.
NOTE: name for app and project should be different
first create a project with projectname
django-admin.py startproject Projectname .
Then create app with appname. (to create your app make sure you are in the same directory manage.py and type this command)
python manage.py startapp Appname
It's the process how I got my doubt clear.
First, I created a directory inside my project directory and put __init__.py, models.py, admin.py, apps.py & views.py.
Then I ran python manage.py runserver & It work well.
Then as suggested on that page I used startapp command. I got this error :
CommandError: 'ucportal' conflicts with the name of an existing Python
module and cannot be used as an app name. Please try another name.
After that I deleted that directory and ran startapp command with same name and it worked fine.
So 'startapp' command is to create an app automatically. If you already have one there, it fails.
Answer given by #DAG worked for me.
I ran into this issue while trying to set up a Wagtail project.
Before creating the app, I had created and activated a virtualenv (using virtualenvwrapper) with the same name: $APPNAME. When I then ran wagtail start $APPNAME, Django looks for naming conflics in the $PYTHONPATH which in this instance points to /Users/User/.virtualenvs.
Naturally, this results in a conflict as /Users/User/.virtualenvs/$APPNAME already exists.
None of these answers helped me. In the end I ended up creating an app with a different name and then just renaming the directory to the app name I wanted all along. Note that you also will need to change the class name in apps.py to match your app name.
Just Simply Use This command
for Django Project Creation
python -m django startproject name_of_django_Project
for Django App Creation
python -m django startapp App_name
I had the same issue when working with wagtail cms. I got this error even there is no such a created app. This occurs when there is an app already that has the same name you need to create inside the site-packages directory.
Once you get this error, you need to check the following directory,
C:\Users\{user}\AppData\Local\Programs\Python\Python38-32\Lib\site-packages
If there is a package with the name same you want to create then you need to remove that package. Also make sure to check that package is important or not before deleting.
The application directory should be created first.
Example: apps/practice
The command appears to be duplicated, but it is correct.
Example: python manage.py startapp practice ./apps1/practice