New to Python - Django manage.py runserver invalid syntax - python

I'm setting up a new environment for a new project and I'm getting an SyntaxError: invalid syntax when running python manage.py runserver
Greater details
File "manage.py", line 16
) from exc
^
SyntaxError: invalid syntax
Manage.py
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'personal_portfolio.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

It's like #Michael Butscher said, you're running it with python 2.0 and that is what is giving the problem.
Try running it like python3 manage.py. When you have both python 2 and python 3 installed in your system, running python runs python2.
Hope that helps.

Related

Error when running custom manage.py command

I'm building a multitenant app based on this page https://www.section.io/engineering-education/implement-multitenancy-with-multiple-databases-in-django/#use-middlewares-for-tenant-specific-database-routing.
It asks to create a custom manage.py (named myapp_manage.py) to create a superuser, so that way I can point the database that I want to run the command like this:
python myapp_manage.py databasename createsuperuser --database=databasename
Everything was ok, I could run the command without problems, but now, when I try to run it, it gives me an error:
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
I don't understand why this error is showing because the environment in custom manage.py is configured exactly like the standard manage.py.
Custom manage.py:
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
from myapp.middleware import set_db_for_router
if __name__ == "__main__":
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'al_project.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
# new
from django.db import connection
args = sys.argv
db = args[1]
with connection.cursor() as cursor:
set_db_for_router(db)
del args[1]
execute_from_command_line(args)
Standard manage.py:
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'al_project.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
So, the line 'os.environ.setdefault' is the same in both files and I can run manage.py commands without any issues, which I understand is indication that the path to the file is correct, but I can't run the myapp_manage.py command (the file is located in the same path as the manage.py file).
I did update Django yesterday, but executed the command today for the first time with no problems. The second time that I tried, I received the error. What could be wrong?

Python manage.py runserver throws an error

I have been running my python server for a few months now and I have had no problems, but ever since I have installed react-native I now get the following error. I don't know if the python problem is related to the installation of react-native but it seems like a bit of coincidence.
Any help in solving this issue would be appreciated
File "manage.py", line 14
) from exc
^
SyntaxError: invalid syntax code here
My manage.py file:
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_website.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
I fixed this my installing python 3.7 and running
py -3 manage.py runserver
I also had to reinstall the packages that were being used on my project
You are trying to use a Python-3-specific Django version with a Python 2 interpreter. You will clearly see that if you look at the top of the full stacktrace
raise ... from ... is a Python 3 syntax. A Python 2 interpreter will treat it as a SyntaxError as can be demonstrated here.
Make sure you are using Python 3 to execute this server.

Basic Flask Issue w/ Importing

I'm following a Flask tutorial and am getting an import error. I have a file called run.py which contains:
from app import app
app.run(debug = True)
When I run ./run.py, I get:
Traceback (most recent call last):
File "./run.py", line 2, in <module>
from app import app
File "/Users/myName/Desktop/SquashScraper/app/__init__.py", line 1, in <module>
from flask import Flask
ImportError: cannot import name Flask
This seems similar to this issue: http://stackoverflow.com/questions/26960235/python3-cannot-import-name-flask
So I attempted the checked solution by running:
virtualenv -p /usr/bin/python3 my_py3_env
Unfortunately, I get:
The executable /usr/bin/python3 (from --python=/usr/bin/python3) does not exist
Any ideas what may be happening here?
Thanks for the help,
bclayman
If you want your virtual environment to be Python 3 but don't know the installation directory, use which python3. Use that directory in your virtualenv -p [directory] my_py3_env command to set up the Python 3 virtual environment.
I sounds like your pip is installing to your Python 2.X directory. If you're okay with that, you'll need to run the app either with python2 run.py, python2.X run.py where x is your installed version, or change the symlink of python in /usr/bin/python to your installation of Python 2.
This question has some more information.
Regardless of the version of Python that you wish to use, you will need to install Flask to that version of Python. See this question for that.

getting raise KeyError(key) KeyError: 'SECRET_KEY' with django on production settings

I've 2 separate settings files for production and development and a common base.py settings file
base.py
SECRET_KEY = r"!##$%^&123456"
prod.py
from .base import *
SECRET_KEY = os.environ['SECRET_KEY']
manage.py
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.dev")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
When I enter this in terminal:
python manage.py shell --settings=entri.settings.prod
I get error:
raise KeyError(key)
KeyError: 'SECRET_KEY'
Help me, I'm new to django and python
I think you are trying this locally, and don't have the SECRET_KEY setup in your environment.
Set it using
export SECRET_KEY="somesecretvalue"
and then running python manage.py shell --settings=entri.settings.prod should work fine.
I use os.getenv('SECRET_KEY'), instead of os.environ['SECRET_KEY']
print os.getenv('SECRET_KEY') #returns None if KEY doesn't exist
print os.getenv('SECRET_KEY', 0) #will return 0 if KEY doesn't exist
my python version is 2.7.12
In Django while trying to secure/hide my secret_key, my problem was even after setting the secret_key using the set command on windows, I still got a 'Key must not be empty' error. I solved that by removing all the spaces before and after the assignment operator in the command. In your cmd, write
set SECRET_KEY="kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"
instead of
set SECRET_KEY = "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"

Error "No such file or directory" when running Django ./manage.py

In my django project, the command ./manage.py [command] results in this error message:
: No such file or directory
The command python manage.py [command] works well. I tried with syncdb and runserver.
I tried chmod a+x manage.py, but the problem persists.
My manage.py:
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
I use django 1.4.1 in a virtualenv.
How can I fix this to use manage.py [command]?
Likely, the reason is because your line endings in the manage.py file are \n instead of \r\n. As a result the #! hash-bang is misinterpreted.
This happens to me when I use a Windows based text-editor for my linux connection.
The #! hash-bang line doesn't point to your virtualenv python; replace the first line with:
#!/path/to/virtualenv/bin/python
In my django project, the command ./manage.py [command] results in
this error message:
: No such file or directory
The command python manage.py [command] works well
If specifying the interpreter makes it work, then it is the first line that must be wrong:
#!/usr/bin/env python
Try:
#!/usr/bin/python
(or wherever the interpreter is. Find it with: which python).
In my case, I was erroneously changing the sys.path in my manage.py.
In my case on Windows 7, every else it seems to be, but I've accidentally added an import in a views.py file:
from Scripts.pilprint import description
My software doesn't need this import, maybe with some wrong short-kut, my Eclipse wrote it for me, but removed this line, the problem disappear.
I suppose that description contain some painful character or have a wrong encoding for Windows.

Categories