Django + MongoDB development environment maintenance (in the middle of writing)

environment

Installation

Create virtualenv

mkvirtualenv -p /usr/bin/python2.7 [Project name]

Django + MongoDB installation

pip install git+https://github.com/django-nonrel/django-nonrel.git@master
pip install git+https://github.com/django-nonrel/djangotoolbox.git@master 
pip install git+https://github.com/django-nonrel/mongodb-engine.git@master

py.test installation

pip instal py.test
pip install django_pytest

Project creation

cd [dev directory]
workon [Project name]
django-admin.py startproject [Project name]

Directory structure

cd [Project root]
#For application placement
mkdir apps
touch apps/__init__.py
#Test data, etc.
mkdir fixtures
#Internationalized po/mo file storage
mkdir -p local/ja/LC_MESSAGES
mkdir -p local/en/LC_MESSAGES

# Put project-specific requirements here.
# See http://pip-installer.org/requirement-format.html for more information.
mkdir requirements

# This directory is used to store static assets for 
# your project. User media files (FileFields/ImageFields) are not stored here.
mkdir static
mkdir static/img
mkdir static/js
mkdir static/css

#Template storage
mkdir templates

#Document storage
mkdir docs

Application creation

cd [Project root]/apps
#For model placement
django-admin.py startapp models

GitHub registration

cd [Project root]
git config --global user.name  "User name"
git config --global user.email  "mail address"
git init
git add *.py
git add app
git commit -m 'first commit'
git remote add origin [email protected]:USER_ID/REPO_NAME.git
git push -u origin master

Preparing MongoDB

Server settings

Creating directories and settings

mkdir -p environment/dev/var/mongodb
mkdir -p environment/dev/etc

#Create configuration file
cat <<EOF >> environment/dev/etc/mongod.conf
heredoc> # Store data
heredoc> dbpath = [Project root]/environment/dev/var/mongodb
heredoc> 
heredoc> # Only accept local connections
heredoc> bind_ip = 127.0.0.1
heredoc> EOF

#Prevent development DB from entering git
cat << EOF >> environment/dev/var/mongodb/README
heredoc>Development MongoDB data storage
heredoc> EOF

cat << EOF >> environment/dev/var/mongodb/.gitignore
heredoc> /*
heredoc> /.*
heredoc> !README
heredoc> !.gitignore
heredoc> EOF

Server startup

mongod run --config environment/dev/etc/mongod.conf

Server initialization

mongo
> use [DB name]
> db.addUser('[DB username]', '[DB password]')

Change DB settings in settings.py

settings.py


DATABASES = {
    'default': {
        'ENGINE': 'django_mongodb_engine', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '[DB name]',                      # Or path to database file if using sqlite3.
        'USER': '[DB username]',                      # Not used with sqlite3.
        'PASSWORD': '[DB password]',                  # Not used with sqlite3.
        'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': 27017,                      # Set to empty string for default. Not used with sqlite3.
    }
}

** If USER and PASSWORD are set, a login error to the DB will occur in python manage.py test. Therefore, it seems better to set USER ='' and PASSWORD ='' in the development environment. ** **

syncdb

python manage.py syncdb

If you get a SITE_ID error

In MongoDB, the ID must be ObjectID, but Django's SITE_ID is 1 by default, so the following error occurs.

bson.errors.InvalidId: AutoField (default primary key) values must be strings representing an ObjectId on MongoDB (got u'1' instead). Please make sure your SITE_ID contains a valid ObjectId string.

http://django-mongodb.org/troubleshooting.html#site-id-issues Then, you should get the ID to be set in SITE_ID with python manage.py tellsite id, but at this point, there is no record in django_site, so I can't get it.

Therefore, you can create the site manually as follows.

python manage.py shell

>>> from django.contrib.sites.models import Site
>>> s = Site()
>>> s.save()
>>> quit()

python manage.py tellsiteid

Set the SITE_ID you got with this in settings.py.

settings.py


SITE_ID = u'XXXXXXXXXXXXXXXXX'

I thought, but in the end I couldn't prevent this error from appearing during test.

The cause is django / contrib / sites / management.py. Here, pk = 1 is forcibly inserted when creating the Site.

django/contrib/sites/management.py


def create_default_site(app, created_models, verbosity, db, **kwargs):
    # Only create the default sites in databases where Django created the table
    if Site in created_models and router.allow_syncdb(db, Site) :
        if verbosity >= 2:
            print "Creating example.com Site object"
        # The default settings set SITE_ID = 1, and some tests in Django's test
        # suite rely on this value. However, if database sequences are reused
        # (e.g. in the test suite after flush/syncdb), it isn't guaranteed that
        # the next id will be 1, so we coerce it. See #15573 and #16353. This
        # can also crop up outside of tests - see #15346.
        s = Site(pk=1, domain="example.com", name="example.com")
        s.save(using=db)
    Site.objects.clear_cache()

signals.post_syncdb.connect(create_default_site, sender=site_app)

It's a hassle, so I stopped using django.contrib.auth and django.contrib.sites with INSTALL_APPS.

settings.py


INSTALLED_APPS = (
    #'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    #'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

Recommended Posts

Django + MongoDB development environment maintenance (in the middle of writing)
Django cannot be installed in the development environment of pipenv + pyenv
In the middle of development, we will introduce Alembic
The meaning of ".object" in Django
Using TensorFlow in the cloud integrated development environment Cloud9 ~ Basics of usage ~
Build the fastest Django development environment with docker-compose
Instantiation of the BOX development environment created earlier
The story of viewing media files in Django
Development environment in Python
[Memo] Django development environment
Used from the introduction of Node.js in WSL environment
Operate mongoDB from python in ubuntu environment ① Introduction of mongoDB
The story of building the fastest Linux environment in the world
Switch the setting value of setting.py according to the development environment
I participated in the translation activity of Django official documents
Unify the environment of the Python development team starting with Poetry
Check the operation of Python for .NET in each environment
Django development environment construction memo
Commands often used in the development environment during Python implementation
Summary of stumbling blocks in Django for the first time
The image is displayed in the local development environment, but the image is not displayed on the remote server of VPS
Django environment development on Windows 10
(Note) Django in Vagrant environment
[Tips] Problems and solutions in the development of python + kivy
django project development environment construction
Make SIP Server as concise as possible (in the middle of explanation)
How to handle multiple versions of CUDA in the same environment
Sphinx single html suppresses page breaks in the middle of the table
[Understanding in the figure] Management of Python virtual environment by Pipenv
LINEbot development, I want to check the operation in the local environment
How to set up the development environment of ev3dev [Windows version]
Trial of writing the configuration file in Python instead of .ini etc.
The story of participating in AtCoder
[Django] Memorandum of environment construction procedure
Implementation of login function in Django
[For beginners] Django -Development environment construction-
Switch the language displayed in Django 1.9
The story of the "hole" in the file
Checking the NAOqi Python development environment
The story of writing a program
Prepare the development environment with anyenv
Get the query string (query string) in Django
Development of MTG card evaluation posting site ~ Django app release in 5 weeks ~
Guidelines for reincarnating in the world of linux programming development (C / C ++ language)
pyenv + pyenv-Automatically load the virtualenv environment in the virtualenv environment
Consider the description of Dockerfile (Django + MySQL②)
Install Django in a pipenv virtual environment
Get the client's IP address in Django
I tried the asynchronous server of Django 3.0
Addition of local development environment on MacOS
Check the behavior of destructor in Python
The story of an error in PyOCR
Understand the benefits of the Django Rest Framework
Django ~ Let's display it in the browser ~
How to check the version of Django
Algorithm Gymnastics 24 Middle of the Linked List
CSS environment created in 10 minutes using Django
Implement part of the process in C ++
About the virtual environment of python version 3.7
Build the execution environment of Jupyter Lab
The result of installing python in Anaconda