I have installed qpydjango on my android phone and the sample project works perfectly. I have been trying start a new project(django website) but have not succeeded.
I've tried running "django-admin.py startproject mysite" but I get this error
syntax error or django is not defined.
Since I haven't gotten any answer from anyone I come up with the following in case anyone has the same question.
#qpy:console
import os
import os.path
projectname=raw_input("Enter project name: ")
projectdir="/mnt/sdcard/com.hipipal.qpyplus/projects/"+projectname
if os.path.exists(projectdir):
print "sorry project '"+projectname+"' already exists"
else:
print "Starting django project '"+projectname+"'"
os.makedirs(projectdir)
os.system("cd /mnt/sdcard/com.hipipal.qpyplus/lib/python2.7/site-packages/django/bin && python django-admin.py startproject "+projectname+" "+projectdir)
appname=raw_input("Enter your first app name: ")
print "Starting the first django app '"+appname+"'"
os.system("cd "+projectdir+" && python manage.py startapp "+appname)
print "You project and first app started successfully"
print "Find the project here '"+projectdir+"'"
print " and edit settings.py as necessory"
print " then run python manage.py runserver to start"
Thank you
download this version of django using pip.
pip install django==1.8.16
It works for me
Related
(I am aware that a number of Django users have had the same issue.
I have looked at a number of solutions online but none has worked for me so far.)
I have set up my apps.py, settings.py and models.py files as explained in Django official tutorial (please see the 3 files below).
When I enter in the terminal:
$ python3 manage.py makemigrations munichliving_app
It returns:
No changes detected in app 'munichliving_app'
(file settings.py) in INSTALLED_APP --> I added and tested both one at a time:
'munichliving_app' and
'munichliving_app.apps.MunichLivingConfig'
apps.py file: https://pastebin.com/raw/qaYy1x44
setting.py file: https://pastebin.com/raw/cSsbfPsx
models.py: https://pastebin.com/raw/U0QeM16k
Django official tutorial states that I should see something along the lines of:
Migrations for 'polls':
polls/migrations/0001_initial.py:
- Create model Choice
- Create model Question
- Add field question to choice
Thank you.
Your app is munichliving (the module that contains models.py), but you have munichliving_app in your INSTALLED_APPS setting. The munichlivin_app is the project folder (the one that contains settings.py). It doesn't normally contain models so you shouldn't usually have to add it to INSTALLED_APPS or make migrations for it.
Replace 'munichliving_app' with 'munichliving' in your INSTALLED_APPS.
Next, I would remove your apps.py because it doesn't appear to be used. If you do keep it, then change it to name='munichliving', then use'munichliving.apps.MunichLivingConfig'inINSTALLED_APPS`.
Finally, create migrations with
./manage.py makemigrations munichliving
Try this:
python manage.py migrate --fake appname
Or delete the migration folder in your app, go to the database and delete the file in django_migrations table, then migrate again:
python manage.py makemigrations
python manage.py migrate
Python 2.7
Django 1.10
settings.ini file(located at "/opts/myproject/settings.ini"):
[settings]
DEBUG: True
SECRET_KEY: '5a88V*GuaQgAZa8W2XgvD%dDogQU9Gcc5juq%ax64kyqmzv2rG'
On my django settings file I have:
import os
from ConfigParser import RawConfigParser
config = RawConfigParser()
config.read('/opts/myproject/settings.ini')
SECRET_KEY = config.get('settings', 'SECRET_KEY')
DEBUG = config.get('settings', 'DEBUG')
The setup works fine locally, but when I deploy to my server I get the following error if I try run any django management commands:
ConfigParser.NoSectionError: No section: 'settings'
If I go into Python shell locally I type in the above imports and read the file I get back:
['/opts/myproject/settings.ini']
On server I get back:
[]
I have tried changing "confif.read()" to "config.readfp()" as suggested on here but it didn't work.
Any help or advice is appreciated.
I have been stuck to a bottleneck which I have tried to resolve using official docs and other answers here in stackoverflow but still not able to create django superuser programatically in the beanstalk environment.
Current state -
a. Application is getting deployed smoothly and I am able to access database from my UI application. basically the entry is getting made in some other table that i have in application.
How I have tried to create superuser -
a. By passing container commands -
Option 1-
container_commands:
01_migrate:
command: "django-admin.py migrate"
leader_only: true
02_collectstatic:
command: "django-admin.py collectstatic --noinput"
commands:
super_user:
command: "source /opt/python/run/venv/bin/activate && python <appname>/createuser.py"
leader_only: true
option_settings:
"aws:elasticbeanstalk:application:environment":
DJANGO_SETTINGS_MODULE: "<Appname>.settings"
PYTHONPATH: "/opt/python/current/app:$PYTHONPATH"
In the logs -
I didn't see it trying to run the custom command.
Option 2 -
container_commands:
01_migrate:
command: "django-admin.py migrate"
leader_only: true
02_collectstatic:
command: "django-admin.py collectstatic --noinput"
03_createsuperuser:
command: "source /opt/python/run/venv/bin/activate && django-admin.py createsuperuser"
option_settings:
"aws:elasticbeanstalk:application:environment":
DJANGO_SETTINGS_MODULE: "<appname>.settings"
PYTHONPATH: "/opt/python/current/app:$PYTHONPATH"
For this, I created a createsuperuser.py file under /management/commands/ following the structure of init.py in both folders and one createsuperuser.py under commands -
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
class Command(BaseCommand):
def handle(self, *args, **options):
if not User.objects.filter(username="admin").exists():
User.objects.create_superuser("admin", "admin#gmail.com", "admin")
On this, I got a following message from logs -
Superuser creation skipped due to not running in a TTY. You can run `manage.py createsuperuser` in your project to create one manually.
My queries are -
why I am not able to create a superuser from command line of my virtual env? In that I am getting a message like this -
raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
A bit weird considering makemigrations command is working fine.
And when I echo $DJANGO_SETTINGS_MODULE, i get the right setting
appname.settings
Let me know where I am going wrong in create superuser thing?
I solved this problem recently with one of my sample app deployment in beanstalk.
I mostly followed the official documentation from this link
In your django app folder create python package 'management'
create another package inside management package 'commands'
create a python file in commands package mysuperuser.py
import os
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
class Command(BaseCommand):
def handle(self, *args, **options):
if not User.objects.filter(username='myuser').exists():
User.objects.create_superuser('myuser',
'myuser#myemail.com',
'mypassword')
In your django-migrate.config file, add a second command
02_create_superuser_for_django_admin:
command: "python manage.py mysuperuser"
leader_only: true
do python manage.py collectstatic and eb deploy.
Doing this created the superuser for me.I didn't have to add any PYTHONPATH as described in some answers available online.
Your custom file is named "createsuperuser.py" that's the same as the Django command, and that collision is what's causing the issue. Use "createsu.py" for the file name, then be sure to change the config file to also use "createsu."
I spent ages working out how to do this and this is by far the simplest & most secure way. Create the following file .platform > hooks > postdeploy > 01_migrate.sh and input the below:
#!/bin/bash
source /var/app/venv/*/bin/activate && { python migrate.py createsuperuser --noinput; }
You can then add DJANGO_SUPERUSER_PASSWORD, DJANGO_SUPERUSER_USERNAME, DJANGO_SUPERUSER_EMAIL to the configuration section of the application environment and it will know these are to be used as we have specified --noinput.
Then add the below to the folder .ebextentions > django.config . This just gets round permission issues in running 01_migrate.sh
container_commands:
01_chmod1:
command: "chmod +x .platform/hooks/postdeploy/01_migrate.sh"
That will create your superuser in a secure way, with the same logic you can also run migrations and collect static by adding to the 01_migrate.sh file.
I have a slightly simpler version of #jimbo's answer. Inside .ebextensions/db-migrate.config I have the following:
container_commands:
01_migrate:
command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate"
leader_only: true
02_createsuperuser:
command: "source /var/app/venv/*/bin/activate && python3 manage.py createsuperuser --noinput"
leader_only: true
option_settings:
aws:elasticbeanstalk:application:environment:
DJANGO_SETTINGS_MODULE: <appname>.settings
The key lines there are the 02_createsuperuser container command. Once you've got that, you can set the DJANGO_SUPERUSER_PASSWORD, DJANGO_SUPERUSER_USERNAME, DJANGO_SUPERUSER_EMAIL environment variables in the environment and deploy and you'll be good to go. Once you've got the user created, remove that container command so it's not run again with the next deployment.
deepesh and jimbos combined solution did it for me.
It is particularly useful if you have a custom User.
I will write down the steps.
1 Create the command file under management/command. Don't name it createsuperuser.py to avoid conflict.
└-- App_dir
└-- management
|-- __init__.py
└-- commands
|-- __init__.py
└-- createsu.py
2 The command file should look like this.
import os
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Creates a superuser."
def handle(self, *args, **options):
if not User.objects.filter(username="username").exists():
password = os.environ.get("SUPERUSER_PASSWORD")
if password is None:
raise ValueError("Password not found")
User.objects.create_superuser(
username="username",
email="email",
password=password,
)
print("Superuser has been created.")
else:
print("Superuser exists")
3 Add the command in the config (inside .ebextension) file.
container_commands:
...
03_superuser:
command: "source /var/app/venv/*/bin/activate && python3 manage.py createsu"
leader_only: true
4 Add the SUPERUSER_PASSWORD in environment > configuration > Software > Environment properties
5 Commit and eb deploy.
We are still storing raw passwords, which isnt the most secure thing in the world. However its much safer than hardcoding the password in the command file.
You can't use create superuser in a situation where the user can't input the info. See https://realpython.com/blog/python/deploying-a-django-app-to-aws-elastic-beanstalk/#Create.the.Admin.User for a different approach.
So, I am going over "Learn Python The Hard Way" and have an issue with Chapter 50 "Building my first website".
jharvard#appliance (~/Dropbox/Python/gothonweb): ls -R
bin docs gothonweb templates tests
./bin:
app.py
./docs:
./gothonweb:
__init__.py
./templates:
./tests:
__init__.py
Trying to run app.py file with command: $python bin/app.py It supposed to start the server but it does not do anything at all. It just return to a prompt again.
#app.py
import web
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
greeting = "Hello world"
return greeting
if __name__ == "__main__":
app.run
I installed lpthw using pip first.
$pip install lpthw.web
When I run the file it gave me ImportError: no 'web' exists
So I installed webpy myself using with help of http://webpy.org/install
And now I'm getting no result at all.
Python I am using is Python 2.7.8 : Anaconda 2.1.0 . So there must be no conflict. Any suggestions? Thank you.
So, I fixed it successfully but adding parenthesis to the function app.ru()
#app.py
....
greeting = "Hello world"
return greeting
if __name__ == "__main__":
app.run
Is there anyway to load one fixture and have it load multiple fixtures?
I'd ideally like to type:
python manage.py loaddata all_fixtures
And have that load all of the data instead of having to type everything. Is this possible?
Using $ python manage.py loaddata myfixtures/*.json would work as Bash will substitute the wildcard to a list of matching filenames.
I have multiple apps on the project directory and have each app with its 'fixtures' directory. So using some bash I can do:
python3 manage.py loaddata */fixtures/*.json
And that expands all of the json files inside of the fixtures directory on each app in my project. You can test it by simply doing:
ls */fixtures/*.json
Why not create a Makefile that pulls in all your fixtures? eg something like:
load_all_fixtures:
./manage.py loaddata path/to/fixtures/foo.json
./manage.py loaddata path/to/fixtures/bar.json
./manage.py loaddata path/to/fixtures/baz.json
And then at the shell prompt, run
make load_all_fixtures
(This kind of approach is also good for executing unit tests for certain apps only and ignoring others, if need be)
This thread shows up among the first results with a Google search "load data from all fixtures" and doesn't mention what IMO is the correct solution for this, ie the solution that allows you to load any fixtures you want without any wildcard tricks nor a single modification of the settings.py file (I also used to do it this way)
Just make your apps' fixtures directories flat (and not the usual Django scheme that e.g. goes app_name/templates/app_name/mytemplate.html), ie app_name/fixtures/myfixture.[json, yaml, xml]
Here's what the django doc says :
For example:
django-admin loaddata foo/bar/mydata.json
would search /fixtures/foo/bar/mydata.json for each installed application, /foo/bar/mydata.json for each directory in FIXTURE_DIRS, and the literal path foo/bar/mydata.json.
What that means is that if you have a fixtures/myfixture.json in all your app directories, you just have to run
./manage.py loaddata myfixture
to load all the fixtures that are located there within your project ... And that's it ! You can even restrict what apps you load fixtures from by using --app or --exclude arguments.
I'll mention that I use my fixtures only to populate my database while doing some development so I don't mind having a flat structure in my 'fixtures' directories ... But even if you use your fixtures for tests it seems like having a flat structure is the Django-esque way to go, and as
that answer suggests, you would reference the fixture from a specific app by just writing something like :
class MyTestCase(TestCase):
fixtures = ['app_name/fixtures/myfixture.json']
My command is this, simple. (django 1.6)
python manage.py loaddata a.json b.json c.json
If you want to have this work on linux and windows you simply could use this for loading all your json-Fixtures:
import os
files = os.listdir('path/to/my/fixtures')
def loaddata(file):
if os.path.splitext(file)[1] == '.json' and file != 'initial_data.json':
print file
os.system("python manage.py loaddata %s" % file)
map(loaddata, files)
Works for me with Django-admin version 3.1.4
python manage.py loaddata json_file_1 json_file_2
My folder structure is like this -
app_name_1
├──fixtures
├────json_file_1.json
├────json_file_2.json
app_name_2
├──fixtures
├────json_file_3.json
Manage.py loaddata will look automatically in certain places, so if you name your fixtures the same in each app, or put all your fixtures in the same folder it can be easy to load them all. If you have many different fixtures, and need a more complex naming schema, you can easily load all your fixtures using find with -exec
find . -name "*.json" -exec manage.py loaddata {} \;
As I state in this [question][2], I also have this in a fabfile. EDIT: use python manage.py if manage.py is not in your VE path.
If your fixtures are located into the same folder, you can simply ls and xargs: ls myfolder | xargs django-admin loaddata.
Example with this structure:
$ tree fixtures/
root_dir/fixtures/
├── 1_users.json
├── 2_articles.json
└── 3_addresses.json
$ ls -d fixtures/* | xargs django-admin loaddata
would do the same as:
$ django-admin loaddata 1_users.json
$ django-admin loaddata 2_articles.json
$ django-admin loaddata 3_addresses.json
After doing a bit of searching, I ended up writing this script. It searches through all directories named "fixtures" for .json files and runs a "python manage.py loaddata {fixture_name}.json". Sometimes ordering matters for foreign key constraints, so it leaves a fixture in the queue if the constraint cannot be resolved.
(Note: It requires the pip package simple_terminal that I wrote. And I set it up to be run by 'python manage.py runscript ', which requires django-extensions.)
# load_fixture.py
#
# A script that searches for all .json files in fixtures directories
# and loads them into the working database. This is meant to be run after
# dropping and recreating a database then running migrations.
#
# Usage: python manage.py runscript load_fixtures
from simple_terminal import Terminal
from django.core.management import call_command
from django.db.utils import IntegrityError
def load_fixture(fixture_location):
# runs command: python manage.py loaddata <fixture_location>
call_command('loaddata', fixture_location)
def run():
with Terminal() as t:
# get all .json files in a fixtures directory
fixture_locations = t.command(
'find . -name *.json | grep fixtures | grep -v env')
while fixture_locations:
# check that every iteration imports are occuring
errors = []
length_before = len(fixture_locations)
for fl in fixture_locations:
try:
# try to load fixture and if loaded remove it from the array
load_fixture(fl)
print("LOADED: {}".format(fl))
fixture_locations.remove(fl)
except IntegrityError as e:
errors.append(str(e))
# if import did not occur this iteration raise exception due to
# missing foreign key reference
length_after = len(fixture_locations)
if length_before == length_after:
raise IntegrityError(' '.join(errors))
This works well for me; it finds all files located in fixtures directories within the the src directory:
python manage.py loaddata \
$(ls -1 src/**/fixtures/* | tr '\n' '\0' | xargs -0 -n 1 basename | tr '\n' ' ')
python manage.py loaddata ./*/fixtures/*.json
This command will look for the folder fixture in all the directory and then it will pick up all the files with json extension and will install the fixtures.
This way you won't have to have just one folder for fixtures instead you can have fixtures on app level and in multiple apps.
It will work with the ideal folder structure like this -
app_name_1
├──fixtures
├────json_file_1.json
├────json_file_2.json
app_name_2
├──fixtures
├────json_file_3.json