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.
Related
I have inherited a project in Django 1 and I am trying to convert to Django 3.1.3. To complicate things a bit I am running it in a docker container
I have the following code in my app.settings.py:
def generate_secret_key(file_name):
chars = "abcdefghijklmnopqrstuvwxyz0123456789!##$%^&*(-_=+)"
key = get_random_string(50, chars)
with open(file_name, "w") as f:
f.write('SECRET_KEY = "%s"' % key)
try:
from secret_key import *
except ImportError:
SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__))
generate_secret_key(os.path.join(SETTINGS_DIR, "secret_key.py"))
from secret_key import *
when I try building the image the following error occurs:
Traceback (most recent call last):
File "/mcvitty/mcvitty/settings.py", line 234, in <module>
from secret_key import *
ModuleNotFoundError: No module named 'secret_key'
Line 234 is
from secret_key import *
The code was working in Django 1. If no secret key module is found, the function generate_secret_key should run generating the module secret_key.py and the program should procede smoothly but i get an error instead. What is different in Django 3.1.3?
This is my project structure:
mcvitty
|
| manage.py
| mcvitty
|
| settings.py
secret_key should be a path relative to the main Django project or the path relative to your current file. Technically, it should be :
from App_name.file_name import *.
It would be better if you share your project structure.
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'
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.
I am trying to get familiar with Flask-APScheduler plug-in through the following sample code: https://github.com/viniciuschiele/flask-apscheduler/blob/master/examples/jobs.py#L1
My project has the following structure:
backend
run.py
application
__init__.py
utilities
__init__.py
views
models
where,
backend>run.py is:
from application import app
app.run(debug=True)
from application import scheduler
scheduler.start()
backend>application>__init__.py is:
from flask import Flask
app = Flask(__name__)
from application.utilities.views import Config
from flask_apscheduler import APScheduler
app.config.from_object(Config())
scheduler = APScheduler()
scheduler.init_app(app)
backend>application>utilities>__init__.py is empty
backend>application>utilities>models.py is empty
backend>application>utilities>views.py is:
class Config(object):
JOBS = [
{
'id': 'job1',
'func': 'application:utilities:views:job1',
'args': (1, 2),
'trigger': {
'type': 'cron',
'second': 10
}
}
]
def job1(a, b):
print(str(a) + ' ' + str(b))
However, I get the following error:
(env)$ python run.py local
Traceback (most recent call last):
File "run.py", line 1, in <module>
from application import app
File "HOME/backend/application/__init__.py", line 106, in <module>
scheduler.init_app(app)
File "/home/xxxxxx/.anaconda/envs/env/lib/python2.7/site-packages/flask_apscheduler/scheduler.py", line 73, in init_app
self.__load_jobs(app)
File "/home/xxxxxx/.anaconda/envs/env/lib/python2.7/site-packages/flask_apscheduler/scheduler.py", line 136, in __load_jobs
self.__load_job(job, app)
File "/home/xxxxxx/.anaconda/envs/env/lib/python2.7/site-packages/flask_apscheduler/scheduler.py", line 159, in __load_job
func = ref_to_obj(func)
File "/home/xxxxxx/.anaconda/envs/env/lib/python2.7/site-packages/apscheduler/util.py", line 264, in ref_to_obj
raise LookupError('Error resolving reference %s: error looking up object' % ref)
LookupError: Error resolving reference application:utilities:views:job1: error looking up object
Does my structure look like ok? Have a placed the right code in the right place? What should I change to make it work?
Your reference should only have one colon (":"). The colon separates the required import from the variable that has to be looked up. So:
'func': 'application.utilities.views:job1'
I am trying to make a custom management command as show in the docs here: https://docs.djangoproject.com/en/dev/howto/custom-management-commands/
When I try to run the command from my project directory I am experiencing the following error:
AttributeError: 'module' object has no attribute 'Command'
Here is the file:
#event_expiration.py
from django.core.management.base import BaseCommand, CommandError
from app.models import Event
import datetime
class Command(BaseCommand):
help = 'deletes expired events'
def handle(self, *args, **options):
today = datetime.datetime.now()
events = Event.objects.filter(date=datetime.date(2011,11,11))
for e in events:
e.delete()
self.stdout.write('Expired events successfully deleted.')
The command I am running is :
$ python manage.py event_expiration
I've made sure I am adding the event_expiration.py file within management and commands folders and that those folders have init files. those are in one of my app folders.
Am I overlooking something here? Any help is appreciated, thanks!
EDIT:
Fellow SO user Yuji helped me attempt to debug this a bit but we are still stumped. heres what we did:
First, the full traceback and command:
(venv)matt#inspirion14z:~/Dropbox/PROD/ersvp.it$ python manage.py event_expiration
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/matt/Dropbox/PROD/ersvp.it/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/home/matt/Dropbox/PROD/ersvp.it/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/matt/Dropbox/PROD/ersvp.it/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 261, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/home/matt/Dropbox/PROD/ersvp.it/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 70, in load_command_class
return module.Command()
AttributeError: 'module' object has no attribute 'Command'
To see what was going on at django/core/management/init.py", line 70 I placed import pdb; pdb.set_trace() within the file.
While in debug mode we tried:
module.__file__
to check if the module was where expected, and it indeed was, with an output of:
'/home/matt/Dropbox/PROD/ersvp.it/app/management/commands/event_expiration.pyc'
Next, we tried manually importing Command in the shell:
>>> from app.management.commands.event_expiration import Command
Traceback (most recent call last): File "<console>", line 1, in <module> ImportError: cannot import name Command
Still scratching my head!
I ran into the same issue and the problem was that my command class wasn't called exactly Command, as the docs says. Example:
class Command(NoArgsCommand):
# Do something here
What is your file structure like? It should be like so:
app/
__init__.py
management/
__init__.py
commands/
__init__.py
event_expiration.py
If the structure is as above, try the following:
python manage.py shell
>>> from app.management.commands import event_expiration
>>> dir(event_expiration)
['Account', 'BaseCommand', 'Callback', 'Command', 'CommandError', 'Comment', 'Status', 'User', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'clean_phone_number', 'csv', 'models', 'os', 're']
I've listed the pure output of running dir on a management command of my own. Give that a try, and report back what is available to the module. You might find yourself getting an error at this point, which may help diagnose. I'm suspecting a problem with importing django itself. I'm guessing the python manage.py shell will fail, which will mean it's not a problem with your command, but a problem with the project.
Edit 2:
The fact that check_expiration was visible in your dir output supports my theory that the folder structure is amiss in someway. Unless there's specifically a function named that within your module.
Please do the following and show the output:
cd /path/to/app/
find .
Also, show the entire contents of your event_expiration.py file, and the contents of your management/commands/__init__.py file. Be wary of spaces mixed with tabs as whitespace also.
Printing a queryset directly will also cause this error. For instance, I was trying to do something like this (just testing, not a real use case):
def handle(self, *args, **options):
ppl = People.objects.all()
print(ppl)
Resolution:
def handle(self, *args, **options):
ppl = People.objects.all()
print(str(ppl)) # Convert queryset to string
Conclusion: What works in shell doesn't necessarily work in a management command. Would be nice if someone can point out why.
I got this error by importing the regular click module instead of djclick
my_module/management/commands/run_thing.py
# import click # causes the error because not setup like djclick is
import djclick as click
#click.command()
#click.option("--thing", required=True, prompt=True)
def command(thing):
print(f"hi: {thing}"
Example run:
./manage.py run_thing --thing 123
...
hi: 123