createsuperuser invalid syntax in Django - django

I ran into a problem while going through my first Django tutorial.
I didn't create an initial superuser account during syncdb and I'm now trying to create it programmatically. The problem is that I'm getting an invalid syntax error when I run the command:
>>> django-admin.py createsuperuser
File "<stdin>", line 1
django-admin.py createsuperuser
^
SyntaxError: invalid syntax
I am running Django through Python tools for Visual Studio 2010.
Both 'django.contrib.auth' and 'django.contrib.admin' are enabled in settings.py.
Here is the tutorial that I'm following.

Looks like you are running the command in the django shell. You need to run this command in the command prompt/terminal instead.
Demo
(_env)k#dev:~/workspace/prj krav 48 $ ./manage.py shell
In [1]: manage.py createsuperuser
------------------------------------------------------------
File "<ipython console>", line 1
manage.py createsuperuser
^
SyntaxError: invalid syntax
Continued..
In [2]: exit()
Do you really want to exit ([y]/n)? y
(_env)k#dev:~/workspace/prj krav 48 $ ./manage.py createsuperuser
Username:

Related

How can I a Djanog auth user on the command line and not have to manually enter the password?

I'm using Django 3.2 and the auth module. I would like to create a super user on the command line (for eventual inclusion in a docker script). When I try this
$ python manage.py createsuperuser --username=joe --email=joe#example.com
I'm prompted for a password. The module does not seem to support a "--password" argument ...
$ python manage.py createsuperuser --username=joe --email=joe#example.com --password=password
usage: manage.py createsuperuser [-h] [--username USERNAME] [--noinput] [--database DATABASE]
[--email EMAIL] [--version] [-v {0,1,2,3}] [--settings SETTINGS]
[--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]
[--skip-checks]
manage.py createsuperuser: error: unrecognized arguments: --password=password
Is there a way I can auto-create a user without manual intervention?
This is done for security reasons: usually shell command are written to a history file, and if you thus would pass the password as parameter, a hacker could eventually look at the history and thus obtain the password of the superuser. It can read the content of the DJANGO_SUPERUSER_PASSWORD variable to set the password.
You thus can set the password with:
DJANGO_SUPERUSER_PASSWORD=somepassword python manage.py createsuperuser --no-input --username=joe --email=joe#example.com
I would however strongly advise not to set the DJANGO_SUPERUSER_PASSWORD in the script file, but define the environment variable elsewhere.

Django project on Heroku initial data fixture integrityerror

I have deployed my project to Heroku and currently trying to load the data dump from local sqlite database to the Heroku database. The remote database is clean and untouched other than the initial migrate command.
I have tried the following combinations of dump but all of them returned an error
python manage.py dumpdata --exclude contenttypes --> data.json
python manage.py dumpdata --exclude auth.permission --exclude contenttypes --indent 2 > data.json
python manage.py dumpdata --exclude auth.permission --exclude contenttypes --exclude auth.user --indent 2 > data.json
and the error is:
django.db.utils.IntegrityError: Problem installing fixture
'/app/data.json': Could not load wellsurfer.Profile(pk=6): duplicate
key value violates unique constraint "wellsurfer_profile_user_id_key"
DETAIL: Key (user_id)=(1) already exists.
i would like to post the json file here but it is about 120,000 lines. But i can provide specific portions if needed. The error clearly says the key exists but the database is clean in the beginning. Obviously, i am doing something very basic thing wrong and i hope you can point me in the right direction. I have tried recommendations that i found on Stackoverflow with no success. How to manage.py loaddata in Django
I had the same problem, and this is what worked for me
source (local sqlite)
python manage.py dumpdata --natural-foreign --indent 4 > datadump.json
(this will include everything, even the auth app / users)
destination (heroku postgres)
python manage.py migrate
python manage.py shell
>>> from django.contrib.contenttypes.models import ContentType
>>> ContentType.objects.all().delete()
>>> quit()
Finally, run following command to load the json data:
python manage.py loaddata datadump.json

django-user-accounts : no such table: account_passwordhistory

There are a lot of django-related posts with "no such table" error but none are coming from django-user-accounts module.
I am getting this error
sqlite3.OperationalError: no such table: account_passwordhistory
, and here are the steps:
Installed django-user-accounts:
$ pip install django-user-accounts
Collecting django-user-accounts
Downloading https://files.pythonhosted.org/packages/0c/4f/40f76395324d98b7f8717aad7e08ad6f86ba2714eb956be6070e0402988c/django_user_accounts-2.0.3-py2.py3-none-any.whl (106kB)
100% |████████████████████████████████| 112kB 2.8MB/s
.
.
.
Installing collected packages: django-appconf, django-user-accounts
Successfully installed django-appconf-1.0.2 django-user-accounts-2.0.3
in settings.py added
INSTALLED_APPS = [ . . .
'django.contrib.sites',
'account' ]
SITE_ID = 1
MIDDLEWARE = [
.
.
.
'account.middleware.ExpiredPasswordMiddleware',
]
ACCOUNT_PASSWORD_USE_HISTORY = True
ACCOUNT_PASSWORD_EXPIRY = 60 # number of seconds
restarted server and ran : $ python manage.py user_password_history
I got:
Traceback (most recent call last):
File "/Users/ipozdnya/miniconda3/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params)
File "/Users/someuser/miniconda3/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: account_passwordhistory
I realize that account_passwordhistory did not get created at the time of install or some other step. $ python manage.py makemigrations states that No changes detected. Nothing in this doc tells me what to do about it: http://blog.pinaxproject.com/2016/11/22/how-configure-password-expiration-for-your-site/
Thanks
Ok, my problem was that I trusted the output of $ python manage.py makemigrations
that stated that No changes detected. However, when I did run $ python manage.py migrate, it applied a new migration for account_passwordhistory and account_passwordexpire tables just fine:
Applying account.0003_passwordexpiry_passwordhistory... OK
And the tables are in the DB.
Setting my password to expire in 1 second (python manage.py user_password_expiry my_user_name --expire 1) however did not have any effect on the site functionality, but that's a different issue.

How can I perform Django's `syncdb --noinput` with call_command?

>>> 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.

How to initialize django database when using django and south

I try to write a script that will reset and reinitialize the database for a new django application. In order to detect any error I want to check the return code of each command.
#! /bin/env python
import sys, os
def execute⌘:
print(cmd)
ret = os.system(cmd)
if not ret:
sys.exit("Last command failed")
if __name__ == "__main__":
if os.path.isfile('app.sqlite'):
os.unlink('app.sqlite')
execute('python manage.py syncdb --noinput --all') # << this fails
execute('python manage.py migrate --noinput --all')
My problem is that I wasn't able to find a way to safely re-initialize the database. Running migrate fails because it requires syncdb and syncdb fails because it requires migrate.
Do not ask me to ignore the return codes from the commands, I want a solution that is able to properly deal with error codes.
You're using sys.exit() improperly. You could raise Exception("error message").
Also, an error message as to what you're seeing would be helpful to better answer your question.
Does:
./manage.py syncdb --migrate --noinput
solve your issue?
Perhaps you should be checking:
if ret != 0:
raise Exception("error")