I want to use django-mailer without PINAX. When I run ./manager.py send_mail
it prints:
Unknown command: 'send_mail'
Type 'manage.py help' for usage.
How do I fix this?
Python 2.5.1 (r251:54863, Sep 22 2007, 01:43:31)
[GCC 4.2.1 (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.conf import settings
>>> 'mailer' in settings.INSTALLED_APPS
True
>>>
$./manage.py send_mail
Unknown command: 'send_mail'
Type 'manage.py help' for usage.
and I used easy_install django-mailer to install the mailer, and the django version
is
VERSION = (1, 1, 1, 'final', 0)
and mailer version is 0.1.0
A few things to double check:
Did you install django-mailer?
Is mailer in your PYTHONPATH? When you import mailer, are you getting the expected module (version and expected path)?
Is mailer listed in your INSTALLED_APPS?
$ ./manage.py shell
>>> import mailer
>>> mailer.get_version()
'0.1.0'
>>> mailer.__file__
/PATH/TO/YOUR/PYTHON/LIBS/mailer/__init__.py
>>> # did it import? did you get the expected version? expected path?
>>> # good, django-mailer is in your PYTHONPATH. now verify project settings.
>>> from django.conf import settings
>>> 'mailer' in settings.INSTALLED_APPS
True
At this point you should see send_mail in the list of available manage.py subcommands.
$ ./manage.py --help
Usage: manage.py subcommand [options] [args]
[...]
runserver
send_mail
shell
[...]
$
After than you will also want to make sure that you are running ./manage.py send_mail via a cron job.
* * * * * (cd $YOUR_PROJECT; /usr/bin/python manage.py send_mail >> cron_mail.log 2>&1)
0,20,40 * * * * (cd $YOUR_PROJECT; /usr/bin/python manage.py retry_deferred >> cron_mail_deferred.log 2>&1)
There is no need to actually set these two cronjobs up during development, just look for your messages via the admin.
The django-mailer module has usage instructions but this should get you up and running.
Can't you just download it from django-mailer and install it separately?
Related
Learning Python 2.7 and trying to run it on Vagrant.
Steps taken:
Vagrant up
Vagrant ssh
Run command python webserver.py
Issue when I run this command, it gives out an ImportError: No module named BaseHTTPServer. Is this problem related to pg_config.sh? Thank you in advance for helping me understand.
I have checked my python 2.7 directory. BaseHTTPServer.py seems to be there.
from BaseHTTPServer import BaseHTTPRequestHandler, BaseHTTPServer
class WebServerHandler(BaseHTTPRequestHandler):
def do_Get(self):
if self.path.endswith("/hello"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_header()
message = ""
message += "<html><body>Hello!</body></html>"
self.wfile.write(message)
print message
return
else:
self.send_error(404,'File Not Found: %s' % self.path)
def main():
try:
port = 8080
server = HTTPServer(('', port), WebServerHandler)
print "Web Server running on port %s" % port
server.serveforever()
except KeyboardInterrupt:
print " ^C entered, stopping web server...."
server.socket.close()
if _name_ == '__main__':
main()
You may consider switching to python 3.x. This is the updated version of your code in Python 3.7.2. Notice in the code below that the BaseHTTPServer module is changed to http.server in python3 link
from http.server import BaseHTTPRequestHandler, HTTPServer
class WebServerHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path.endswith("/hello"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
message = ""
message += "<html><body>Hello!</body></html>"
self.wfile.write(message)
print (message)
return
else:
self.send_error(404, 'File Not Found: %s' % self.path)
def main():
try:
port = 8080
server = HTTPServer(('', port), WebServerHandler)
print ("Web Server running on port %s" % port)
server.serve_forever()
except KeyboardInterrupt:
print (" ^C entered, stopping web server....")
server.socket.close()
if __name__ == '__main__':
main()
You can follow the link I provided above to read more from the documentation.
Are you sure that the python you are running/testing from the command line is the same python that your script is running?
i.e. BaseHTTPServer might be present in one install, but not the other.
For example, on my machine:
$ which python2.7
/usr/bin/python2.7
Is your "python" (in the command line you specified) the same as "python2.7"?
$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import BaseHTTPServer
>>> BaseHTTPServer
<module 'BaseHTTPServer' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/BaseHTTPServer.pyc'>
Try a module that does exist to ensure the path is what you are expecting.
In python earlier than v3 you need to run http server as
python -m SimpleHTTPServer 8069
if you are using pycharm, change the interpreter to Python 2.7 from the latest version.
If the project Interpreter is not present you can also add one by specifying the python 2.7 install path.
I'm trying to use the intcomma to format my number in template, but it cannot work properly.
{%load humanize%}
{%blocktrans with val=myvalue|intcomma%}The number is {{val}}{%endblocktrans%}
After some searching, I found the django.utils.formats.number_format is not function. Hereunder is my testing:
corpweb#56944bf480d1:~$ ./manage.py shell
Python 3.4.4 (default, Feb 17 2016, 02:50:56)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import locale
>>> from django.utils.formats import number_format
>>> val=123456789
>>> number_format(val,force_grouping=True)
'123456789'
>>> locale.getlocale()
('en_US', 'UTF-8')
>>>
Is there have anything I setup wrong?
When rendering templates or using number_format outside of the Django app flow the translation module is not activated. Here are a few notes and instructions on how to turn on translation in custom management commands.
To make the shell example work we just need to activate the translation module as such:
(venv) $ ./manage.py shell
Python 3.6.4 (default, Mar 1 2018, 18:36:50)
>>> from django.utils.formats import number_format
>>> from django.utils import translation
>>> translation.activate('en-us')
>>> number_format(50000, force_grouping=True)
'50,000'
The key line above is: translation.activate('en-us')
Everything is ok with your setup I guess. Just set USE_L10N = True in your settings.py if it is set to False, as #Tim Schneider mentioned, and you better try it like this {{ val|intcomma }} as #Leonard2 mentioned and it must work. And also as it is mentioned here make sure:
To activate these filters, add 'django.contrib.humanize' to your INSTALLED_APPS setting.
I wrote two scripts: modbus_master.py and modbus_helpers.py.
modbus_helpers.py is just a bunch of raw functions I defined that I'm trying to call from modbus_master.py.
When I try to execute 'modbus_master.py' from the windows CLI this happens...
C:\Python27\modbus_simulator>modbus_master.py
Traceback (most recent call last):
File "C:\Python27\modbus_master.py", line 3, in <module>
import modbus_helpers
ImportError: No module named modbus_helpers
However,
If I go to python interactive mode and do this...
C:\Python27\modbus_simulator>python
Python 2.7.5 (default, May 15 2013, 22:43:36) MSC v.1500 32 bit (Intel) on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import modbus_master
The code in modbus_master.py that calls modbus_helpers.py works just fine. So how do I bridge this gap here so that I can just do this and run the script without error?
C:\Python27\modbus_simulator>modbus_master.py
Code in modbus_master.py:
import sys
import json
import modbus_helpers
import os
def printRegsets():
print 'these register sets were piped in...\r\n'
regsetIndex = 0
for regset in registersetsList:
print str(regsetIndex) , ':', regset['Name']
regsetIndex = regsetIndex + 1
path = os.path.normpath('C:\Python27\modbus_simulator\export2.txt')
registersetsList = modbus_helpers.getRegisterSetFromACMExportFile(path)
printRegsets()
Found the solution to the problem. There was nothing wrong with the code. I missed the obvious...modbus_master.py must be in the same folder/directory as modbus_helpers.py for the 'import' statement to work.
Does anyone have an example of successfully using flask-migrate on pythonanywhere? Does anyone have a simple example of what an app.py using migration should look like? Something along the lines of:
from flask import Flask, request, render_template
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager
app = Flask(__name__ )
app.secret_key = 'This is really unique and secret'
app.config['SQLALCHEMY_DATABASE_URI'] = '<whatever>'
db = SQLAlchemy(app)
db.create_all()
manager = Manager( app )
migrate = Migrate( app, db )
manager.add_command('db', MigrateCommand )
I find that when I try to run
python app.py db init
it fails to generate the migration repository. Could this be a file permission issue on pythonanywhere?
Author of Flask-Migrate here.
The idea is that you generate your db repository in your development environment. You have to commit your repository along with your source files to source control.
Then when you install the application on your hosting service all you need to do is run the upgrade command to get your db created and migrated to the latest revision.
Update: base on your comments below, you want to develop an application from scratch. I just tested this myself, and was able to create a db repository, create a migration, and apply it. What I did is start the pythonanywhere bash console. Here is a copy of my complete session:
17:39 ~ $ mkdir dbtest
17:39 ~ $ cd dbtest
17:39 ~/dbtest $ virtualenv venv
New python executable in venv/bin/python2.7
Also creating executable in venv/bin/python
Installing setuptools............done.
Installing pip...............done.
17:39 ~/dbtest $ . venv/bin/activate
(venv)17:39 ~/dbtest $ pip install flask flask-migrate
...
(venv)17:42 ~/dbtest $ vi dbtest.py
... (entered flask-migrate example code, see below)
(venv)17:47 ~/dbtest $ python dbtest.py
usage: dbtest.py [-?] {shell,db,runserver} ...
positional arguments:
{shell,db,runserver}
shell Runs a Python shell inside Flask application context.
db Perform database migrations
runserver Runs the Flask development server i.e. app.run()
optional arguments:
-?, --help show this help message and exit
(venv)17:47 ~/dbtest $ python dbtest.py db init
Creating directory /home/miguelgrinberg/dbtest/migrations ... done
Creating directory /home/miguelgrinberg/dbtest/migrations/versions ... done
Generating /home/miguelgrinberg/dbtest/migrations/README ... done
Generating /home/miguelgrinberg/dbtest/migrations/alembic.ini ... done
Generating /home/miguelgrinberg/dbtest/migrations/env.py ... done
Generating /home/miguelgrinberg/dbtest/migrations/script.py.mako ... done
Generating /home/miguelgrinberg/dbtest/migrations/env.pyc ... done
Please edit configuration/connection/logging settings in '/home/miguelgrinberg/dbtest/migrations/alembic.ini' before proceeding.
(venv)17:54 ~/dbtest $ python dbtest.py db migrate
INFO [alembic.migration] Context impl SQLiteImpl.
INFO [alembic.migration] Will assume non-transactional DDL.
INFO [alembic.autogenerate.compare] Detected added table 'user'
Generating /home/miguelgrinberg/dbtest/migrations/versions/1c4aa671e23a_.py ... done
(venv)17:54 ~/dbtest $ python dbtest.py db upgrade
INFO [alembic.migration] Context impl SQLiteImpl.
INFO [alembic.migration] Will assume non-transactional DDL.
INFO [alembic.migration] Running upgrade None -> 1c4aa671e23a, empty message
(venv)17:55 ~/dbtest $ ls -l
total 8
-rw-r--r-- 1 miguelgrinberg registered_users 3072 Sep 28 2014 app.db
-rwxrwxr-x 1 miguelgrinberg registered_users 511 Sep 28 17:48 dbtest.py
drwxrwxr-x 3 miguelgrinberg registered_users 100 Sep 28 17:55 migrations
drwxrwxr-x 6 miguelgrinberg registered_users 52 Sep 28 17:41 venv
The example application that I used to test this is below:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(128))
if __name__ == '__main__':
manager.run()
Any chance you already have a migration repository created? Or a database?
>>> from django.core.management import call_command
>>> call_command('syncdb')
executes the syncdb management command from within a python script. However, I want to run the equivalent of
$ python manage.py syncdb --noinput
from within a python shell or script. How can I do that?
The following lines don't work without interrupting me with the question whether I want to create a super user.
>>> call_command('syncdb', noinput = True) # asks for input
>>> call_command('syncdb', 'noinput') # raises an exception
I use Django 1.3.
call_command('syncdb', interactive = False)
EDIT:
I found the answer in the source code. The source code for all management commands can be found in a python module called management/commands/(command_name).py
The python module where the syncdb command resides is django.core.management.commands.syncdb
To find the source code of the command you can do something like this:
(env)$ ./manage.py shell
>>> from django.core.management.commands import syncdb
>>> syncdb.__file__
'/home/user/env/local/lib/python2.7/site-packages/django/core/management/commands/syncdb.pyc'
>>>
Of course, check the contents of syncdb.py, and not syncdb.pyc.
Or looking at the online source, the syncdb.py script contains:
make_option('--noinput', action='store_false', dest='interactive', default=True,
help='Tells Django to NOT prompt the user for input of any kind.'),
that tells us that instead of --noinput on the command line, we should use interactive if we want to automate commands with the call_command function.