Pycharm django tests settings - django

Having troubles running tests in PyCharm.
manage.py test works fine.
But if I run test in PyCharm Django Test getting following error:
AttributeError: 'module' object has no attribute 'ROOT_URLCONF'
Django tests Run\Debug configuration:
DJANGO_SETTINGS_MODULE=project.settings.test
Django Preferences
Settings: project/settings/test.py
Manage Script: project/manage.py
Test
from django.test import SimpleTestCase
from rest_framework import status
class AccountTestCase(SimpleTestCase):
def test_current_account(self):
url = '/api/accounts/current/'
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_301_MOVED_PERMANENTLY)
StackTrace
Error
packages/django/core/handlers/base.py", line 113, in get_response
urlconf = settings.ROOT_URLCONF
File "/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__
return getattr(self._wrapped, name)
File "/lib/python2.7/site-packages/django/conf/__init__.py", line 173, in __getattr__
return getattr(self.default_settings, name)
AttributeError: 'module' object has no attribute 'ROOT_URLCONF'
Would appreciate any help.

Ok got it.
You have to mark root folder in PyCharm as "sources root"
Then I guess it adds it to PYTHONPATH

Verify the Pycharm Tools menu has an item "Run manage.py Task...". If not, configuration changes are needed in File > Settings > Languages & Frameworks > Django. Additionally, if using a remote database, permission to create databases is required.
PyCharm Django projects require some setup to fully use all the IDE features. Many actions run fine, but Django testing does not. When running test.py, the following console messages indicate additional project setup is needed:
There is no such settings file settings
AttributeError: module 'django.conf.global_settings' has no attribute 'ROOT_URLCONF'

Related

Error loading existing db data into Django (fixtures, postgresql)

Am trying to load some generated data into Django without disrupting the existing data in the site. What I have:
Saved the data as a valid JSON (validated here).
The JSON format matches the Django documentation. In previous attempts I also aligned it to the Django documentation here (slightly different field order, the result was the same).
Output errors I'm receiving are very generic and not helpful, even with verbosity=3.
The Error Prompt
Operations to perform:
Apply all migrations: workoutprogrammes
Running migrations:
Applying workoutprogrammes.0005_auto_20220415_2021...Loading '/Users/Robert/Desktop/Projects/Powerlifts/src/workoutprogrammes/fixtures/datafile_2' fixtures...
Checking '/Users/Robert/Desktop/Projects/Powerlifts/src/workoutprogrammes/fixtures' for fixtures...
Installing json fixture 'datafile_2' from '/Users/Robert/Desktop/Projects/Powerlifts/src/workoutprogrammes/fixtures'.
Traceback (most recent call last):
File "/Users/Robert/Desktop/Projects/Powerlifts/venv/lib/python3.8/site-packages/django/core/serializers/json.py", line 70, in Deserializer
yield from PythonDeserializer(objects, **options)
File "/Users/Robert/Desktop/Projects/Powerlifts/venv/lib/python3.8/site-packages/django/core/serializers/python.py", line 93, in Deserializer
Model = _get_model(d["model"])
KeyError: 'model'
The above exception was the direct cause of the following exception:... text continues on...
for obj in objects:
File "/Users/Robert/Desktop/Projects/Powerlifts/venv/lib/python3.8/site-packages/django/core/serializers/json.py", line 74, in Deserializer
raise DeserializationError() from exc
django.core.serializers.base.DeserializationError: Problem installing fixture '/Users/Robert/Desktop/Projects/Powerlifts/src/workoutprogrammes/fixtures/datafile_2.json':
auto_2022_migration.py file:
from django.db import migrations
from django.core.management import call_command
def db_migration(apps, schema_editor):
call_command('loaddata', '/filename.json', verbosity=3)
class Migration(migrations.Migration):
dependencies = [('workoutprogrammes', '0004_extable_delete_ex_table'),]
operations = [migrations.RunPython(db_migration),]
JSON file extract (start... end)
NB: all my PKs are UUIDs generated from postgresql
[{"pk":"af82d5f4-2814-4d52-b2b1-6add6cf18d3c","model":"workoutprogrammes.ex_table","fields":{"exercise_name":"Cable Alternating Front Raise","utility":"Auxiliary","mechanics":"Isolated","force":"Push","levator_scapulae":"Stabilisers",..."obliques":"Stabilisers","psoas_major":""}}]
I'm not sure what the original error was. I suspect it had to do with either editing the table/schema using psql separately from Django, OR using the somewhat outdated uuid-ossp package instead of pgcrypto package (native to Djagno via CryptoExtension()). I was never able to confirm. I did however manage to get it working by:
Deleting the table (schema, data) using psql and the app using Django. Creating a new app in Django.
Load the prev model data into this new_app/models.py. Make new migration file, first updating the CryptoExtension() operation before committing the migration.
Create Fixtures directory and relevant file (per Django specs, validated JSON online.
Validate my UUIDs online
Load the fixture data into the app. python3 manage.py loaddata /path/to/data/file_name.json

Initialising flask environment variable issues

I am trying to create a an application using Flask. I have done this before successfully, however, I am not sure why this is not working this time. Everything seems to be in the right order. I have searched for answers, however, I still can't determine what's going wrong as everything seems logical to me? Yet, it is still going wrong?
ZXM934/
app/
__innit__.py
views.py
venv/
run.py
The following are each files contents:
run.py
# Importing app object which was created in __innit__.py file into app.py
from app import app
if __name__ == "__main__":
app.run()
__innit__.py
# This class will ultimately bring our entire application together.
from flask import Flask
# Creating Flask app.
app = Flask(__name__)
# Importing views file to avoid circular import.
from app import views
view.py
# This class represents the UI of our website.
# Importing app directory. As __innit__.py file is apart of this directory,
# this import treats it as a package.
from app import app
#app.route("/")
def public_home():
return "Homepage"
#app.route("/login")
def login():
return "<h1 style='color: red'>Login</h1>"
I set the environment variables as following within the console:
export FLASK_APP=run.py
export FLASK_ENV=development
I then run the following command:
flask run
The following error occurs:
flask.cli.NoAppException: While importing "run", an ImportError was raised:
Traceback (most recent call last):
File "/Users/zahidmalik-ramzan/Desktop/zxm934/venv/lib/python3.7/site-packages/flask/cli.py", line 240, in locate_app
__import__(module_name)
File "/Users/zahidmalik-ramzan/Desktop/zxm934/run.py", line 2, in <module>
from app import app
ImportError: cannot import name 'app' from 'app' (unknown location)
I don't understand what I am doing wrong?
Your problem is in the file name __innit__.py.
For python to understand that a folder is an actual package within your project structure you need a special file inside, i.e. __init.py__ ps: no double n.
A regular package is typically implemented as a directory containing an __init__.py file. When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package’s namespace.
Conclusion: change your __innit.py__ to __init.py__

Test discovery fails using DRF APITestCase but not django's TestCase

Using Django Rest Framework's APITestCase class, Visual Studio Code does not discover my unittest tests. I've configured vscode to use unittest and given it the path to my django app. I have toggled between jedi and ms's language server for python.
I can run the tests manually, using python manage.py test.
If I switch to using Django's provided django.test.TestCase, vscode discovers the tests and creates the adornments. I have also tried rest_framework's two other test cases: APISimpleTestCase, APITransactionTestCase and neither worked.
My test class is very simple, essentially the following:
from django.test import TestCase
# * cannot get vscode to discover tests with this
from rest_framework.test import APITestCase
service_path = "/api/v0.1/service"
# class PathLookupTests(TestCase):
class PathLookupTests(APISimpleTestCase):
def test_responding(self):
uri = "valid_uri"
resp = self.client.get(f"{service_path}/?uri={uri}")
self.assertEqual(resp.status_code, 200)
In the Python Test Log I saw the following traceback once, but cannot repeat it:
File "/Users/bfalk/miniconda3/envs/web-server-eval/lib/python3.8/site-packages/django/test/testcases.py", line 1123, in setUpClass
super().setUpClass()
File "/Users/bfalk/miniconda3/envs/web-server-eval/lib/python3.8/site-packages/django/test/testcases.py", line 197, in setUpClass
cls._add_databases_failures()
File "/Users/bfalk/miniconda3/envs/web-server-eval/lib/python3.8/site-packages/django/test/testcases.py", line 218, in _add_databases_failures
cls.databases = cls._validate_databases()
File "/Users/bfalk/miniconda3/envs/web-server-eval/lib/python3.8/site-packages/django/test/testcases.py", line 204, in _validate_databases
if alias not in connections:
TypeError: argument of type 'ConnectionHandler' is not iterable
After a bit more digging, I now see that django's test runner does not work in vscode. https://github.com/microsoft/vscode-python/issues/73
The solution, at least for me, was to use pytest-django
Here's the example above but using pytest-django (after setting up my pytest.ini file to point at my django app)
service_path = "/api/v0.1/service"
def test_responding(client):
uri = "valid_uri"
resp = client.get(f"{service_path}/?uri={uri}")
assert resp.status_code == 200

Django Cron ImportError: No module named cron

I'm trying to setup django-cron https://github.com/Tivix/django-cron
I've finished migrating it but running python2.7 manage.py runcrons throws this error
Make sure these are valid cron class names: ['rest.cron.MyCronJob']
Traceback (most recent call last):
File "/home/kbuzz/lib/python2.7/django_cron/management/commands/runcrons.py", line 35, in handle
crons_to_run = [get_class(x) for x in cron_class_names]
File "/home/kbuzz/lib/python2.7/django_cron/__init__.py", line 23, in get_class
m = __import__(module)
ImportError: No module named cron
I created a file cron.py in the app rest and also added the same code to views
from django_cron import CronJobBase, Schedule
import datetime
class MyCronJob(CronJobBase):
RUN_EVERY_MINS = 10 # every 10 minutes
schedule = Schedule(run_every_mins=RUN_EVERY_MINS)
code = 'rest.movies_cron' # a unique code
def do(self):
check = file('test.txt','a')
today = datetime.datetime.now()
check.write(today.isoformat())
check.close()
In the settings file I added this, I expect it's a linking issue (code not found).
CRON_CLASSES = [
"rest.cron.MyCronJob",
]
I had the same issue. cron.py should be inside of the rest app folder not the rest project folder. I have a hunch that you had the cron.py inside the rest project folder.

Django + heroku - import error on line that doesn't exist

I'm new to django (using python 2.7) and I was just trying to use heroku for the first time but I always get the following error:
remote: -----> Preparing static assets
remote: Collectstatic configuration error. To debug, run:
remote: $ heroku run python manage.py collectstatic --noinput
When I run that command, an import error regarding the django registration redux library shows up. I've had this problem before in Django and I fixed it by placing RequestSite under 'requests' and Site under 'models'. That solved the problem but the error still shows up in Heroku.
(venv) C:\Users\Carolina\Desktop\Coding\venv\project1>heroku run python manage.p
y collectstatic --noinput
Running python manage.py collectstatic --noinput on acla-acla... up, run.3645
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/_
_init__.py", line 350, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/_
_init__.py", line 324, in execute
django.setup()
File "/app/.heroku/python/lib/python2.7/site-packages/django/__init__.py", lin
e 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/app/.heroku/python/lib/python2.7/site-packages/django/apps/registry.py"
, line 115, in populate
app_config.ready()
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/app
s.py", line 22, in ready
self.module.autodiscover()
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/__i
nit__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/module_load
ing.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/app/.heroku/python/lib/python2.7/importlib/__init__.py", line 37, in im
port_module
__import__(name)
File "/app/.heroku/python/lib/python2.7/site-packages/registration/admin.py",
line 2, in <module>
from django.contrib.sites.models import RequestSite
ImportError: cannot import name RequestSite
The thing is - that line doesn't exist. I went to venv/lib/site-packages/registration/admin.py and line 2 is this one:
from django.contrib import admin
from django.contrib.sites.requests import RequestSite # HERE
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from registration.models import RegistrationProfile
from registration.users import UsernameField
class RegistrationAdmin(admin.ModelAdmin):
actions = ['activate_users', 'resend_activation_email']
list_display = ('user', 'activation_key_expired')
raw_id_fields = ['user']
search_fields = ('user__{0}'.format(UsernameField()), 'user__first_name', 'user__last_name')
def activate_users(self, request, queryset):
"""
Activates the selected users, if they are not already
activated.
"""
for profile in queryset:
RegistrationProfile.objects.activate_user(profile.activation_key)
activate_users.short_description = _("Activate users")
def resend_activation_email(self, request, queryset):
"""
Re-sends activation emails for the selected users.
Note that this will *only* send activation emails for users
who are eligible to activate; emails will not be sent to users
whose activation keys have expired or who have already
activated.
"""
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
for profile in queryset:
if not profile.activation_key_expired():
profile.send_activation_email(site)
resend_activation_email.short_description = _("Re-send activation emails")
admin.site.register(RegistrationProfile, RegistrationAdmin)
This is what I get with pip freeze, just in case:
Django==1.9
django-crispy-forms==1.5.2
django-registration==2.0.3
django-registration-redux==1.2
django-tinymce==2.2.0
Pillow==3.0.0
requests==2.9.0
South==1.0.2
stripe==1.27.1
wheel==0.24.0
Anyone knows why this is happening? Thanks in advance!
EDIT ----
Ok, so the problem was the one mentioned by Daniel Roseman. The library is broken in pypi and I had to tell heroku to install it from github (where the package is fixed).
So, I went to my requirements.txt file and replaced this line:
django-registration-redux==1.2
with this one:
-e git://github.com/macropin/django-registration.git#egg=django-registration==1.2
(I also removed 'django-registration==2.0.3' because it is an old version of django-registration-redux and was creating problems).
Hope this helps people with the same issue!
It sounds like you edited the code for your locally installed copy of django-registration-redux. But that won't have any effect on Heroku, since the library will be installed directly from PyPI, according to the version in your requirements.txt.
If the library is really broken, you will need to fork it and point your requirements.txt to your fixed version. However, looking at the code on GitHub, it doesn't actually seem to be broken; you just need to update the version you are pointing to.