setup.py
.Translator's Note:
First, create a directory (tutorial
) in which we will work:
~$ mkdir tutorial ~$ cd tutorial ~/tutorial$ mkdir venv project
Our virtual environment will be located in thevenv
directory, and theproject
directory will contain the Django project.
~/tutorial$ virtualenv --prompt="(venv:tutorial)" ./venv/ New python executable in ./venv/bin/python Installing setuptools............done. Installing pip...............done. ~/tutorial$ source ./venv/bin/activate (venv:tutorial)~/tutorial$
requirements.txt
file in the tutorial
directory with a single line (dependency) in it:
Django==1.6.7
Translator's Note:
In case you want to use the latest version of Django (1.7 - at the time of writing the translation) - instead of the lineDjango==1.6.7
just leaveDjango
- pip installs the latest available version.
(venv:tutorial)~/tutorial$ pip install -U -r requirements.txt Downloadping/unpacking Django==1.6.7 (from -r requirements.txt (line 1)) Downloading Django-1.6.7.tar.gz (6.6MB): 6.6MB downloaded Running setup.py egg_info for package Django warning: no previously-included files matching '__pycache__' found under directory '*' warning: no previously-included files matching '*.py[co]' found under directory '*' Installing collected packages: Django Running setup.py install for Django changing mode of build/scripts-2.7/django-admin.py from 644 to 755 warning: no previously-included files matching '__pycache__' found under directory '*' warning: no previously-included files matching '*.py[co]' found under directory '*' changing mode of /home/nathan/p/edt/bin/django-admin.py to 755 Successfully installed Django Cleaning up...
django-admin.py
script into the system to handle scaffolding tasks. To create project files, use the startproject
task. We will define the name of the project and the name of the directory in which we want to place the project. Since we are already in an isolated environment, we can simply write:
Translator's Note:
Let's go to the~/tutorial/project/
directory and in the future we will work only from this directory (by$
we will mean~/tutorial/project/$
):
(venv:tutorial)~/tutorial/$ cd project
(venv:tutorial)$ django-admin.py startproject addressbook .
manage.py ./addressbook __init__.py settings.py urls.py wsgi.py
manage.py
is a link to the django-admin
script, but with pre-installed environment variables pointing to your project, both for reading settings from there and for managing it if necessary;settings.py
- here are your project settings. The file already contains some reasonable settings, but the database is not specified;urls.py
- contains URLs for mapping (displaying) views: we will soon ( in later chapters ) talk more about this;wsgi.py
is a WSGI wrapper for your application. This file is used by the Django development server and possibly other containers, such as mod_wsgi
, uwsgi
and others on a “combat” server. (venv:tutorial)$ python ./manage.py startapp contacts
./contacts __init__.py models.py tests.py views.py
models.py
will contain Django ORM models for your application;views.py
will contain the view code;tests.py
will contain the unit tests and integration tests you have written.admin.py
will contain the model for the administrative interface.migrations/
contains migration filesTranslator's Note:
Currently, our~/tutorial/
directory contains the dependencies file (requirements.txt
), the virtual environment directory (venv/
), one project (project/addressbook
), and one application (project/contacts
) and has the following contents:
~/tutorial/ requirements.txt venv/ ... project/ manage.py addressbook/ __init__.py settings.py urls.py wsgi.py contacts/ __init__.py models.py tests.py views.py
requirements.txt
.
DATABASES
definition in the addressbook/settings.py
file. The settings.py file contains the Django settings for our project. It has several settings that you must specify - for example, DATABASES
- as well as other, optional, settings. Django sets up some of the settings itself when it generates a project. The documentation contains a complete list of settings . In addition, you can add your own settings if necessary.
ENGINE
) and the name of the database ( NAME
). SQLite interprets the database name as the file name for the database:
DATABASES = { 'defaults': { 'ENGINE': 'django.db.backends.sqlite3,' # 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': os.path.join(BASE_DIR, 'address.db'), 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } }
django.conf.settings
. You typically import settings from django.conf
:
from django.conf import settings
Contacts
model for our application in the contacts/models.py
:
from django.db import models class Contact(models.Model): first_name = models.CharField( max_length=255, ) last_name = models.CharField( max_length=255, ) email = models.EmailField() def __str__(self): return ' '.join([ self.first_name, self.last_name, ])
EmailField
, which we used, is a mapping to a column with type CharField
, but adds validation data.
syncdb
looks at the installed models and creates (if necessary) tables for them:
Translator's Note:
Django will offer to create a superuser for Android, which is enabled by default in this version. Take advantage of his offer.
Translator's Note:
Since Django 1.7, native support for migrations has been added to the framework and thesyncdb
been deprecated. So be so kind as to use themigrate
syncdb
instead ofsyncdb
.
(venv:tutorial)$ python ./manage.py syncdb Creating tables ... Creating table django_admin_log Creating table auth_permission Creating table auth_group_permissions Creating table auth_group Creating table auth_user_groups Creating table auth_user_user_permissions Creating table auth_user Creating table django_content_type Creating table django_session You just installed Django's auth system, which means you don't have any superusers defined. Would you like to create one now? (yes/no): yes Username (leave blank to use 'bjakushka'): Email address: Password: Password (again): Superuser created successfully. Installing custom SQL ... installing indexes ... Installed 0 object(s) from 0 fixture(s) (venv:tutorial)$
Translator's Note:
If you are using Django version 1.7 and higher, the output will be as follows:
(venv:tutorial)$ python ./manage.py migrate Opperation to perform: Apply all migrations: admin, contenttypes, auth, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying sessions.0001_initial... OK (venv:tutorial)$
INSTALLED_APPS
contains a list of applications used in the project. This list contains strings that display Python packages. Django will import each of the specified packages, and then watch the models
module. Let's add our contacts
application to the project settings ( addressbook/settings.py
):
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'contacts', )
syncdb
again:Translator's Note:
For Django version 1.7 and higher, you will need to first run themakemigrations
command - to create migrations based on changes in models, and then execute themigrate
command - in order to apply the created migrations.
(venv:tutorial)$ python ./manage.py syncdb Creating tables ... Creating table contacts_contact Installing custom SQL ... Installing indexes ... Installed 0 object(s) from 0 fixture(s) (venv:tutorial)$
Translator's Note:
Conclusion for Django 1.7 and higher:
(venv:tutorial)$ python ./manage.py makemigrations Migrations for 'contacts': 0001_initial.py: - Create model Contact (venv:tutorial)$ python ./manage.py migrate Opperation to perform: Apply all migrations: admin, contenttypes, sessions, auth, contacts Running migrations: Applying contacts.0001_initial... OK (venv:tutorial)$
contacts_contact
: by default, Dj ango gives tables a name using a combination of application name and model name. You can change this with options in the Meta model.
(venv:tutorial)$ python ./manage.py shell Python 2.7.3 (default, Mar 14 2014, 11:57:14) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from contacts.models import Contact >>> Contact.objects.all() [] >>> Contact.objects.create(first_name='Nathan', last_name='Yergler') <Contact: Nathan Yergler> >>> Contact.objects.all() [<Contact: Nathan Yergler>] >>> nathan = Contact.objects.get(first_name='Nathan') >>> nathan <Contact: Nathan Yergler> >>> print nathan Nathan Yergler >>> nathan.id 1
manage.py shell
command runs the Python interactive shell for us with the correct paths for Django. If you try to start the Python interpreter and just import your applications, an exception will be thrown, because Django does not know which settings to use, and cannot display the model instances on the database.
objects
our model were used here. This is the model manager . So, if a single instance of a model is an analogy for a row in a database, then the model manager is an analogy for a table. By default, the model manager provides query functionality and can be configured. When we call all()
, filter()
or the manager itself, the QuerySet
object is returned. QuerySet
is an iterable object and loads data from the database as needed.
id
, which we did not define in our model, was used above. Django adds this field as the primary key for the model, but only if you yourself have not determined which field will be the primary key .
__str__
, so it is time to write the tests. The __str__
method will be used in just a few places, and it is quite possible that it will be fully shown to the end user . For this method it is worth writing a test, while we understand how it works . Django created the tests.py
file when it created the application, so we will add the first test to this file, the contacts
application.
from django.test import TestCase from contacts.models import Contact class ContactTests(TestCase): """Contact model tests.""" def test_str(self): contact = Contact(first_name='John', last_name='Smith') self.assertEquals( str(contact), 'John Smith', )
manage.py test
command:
(venv:tutorial)$ python ./manage.py test
contacts
application to our project, you could see that several built-in Django applications were added by default. An additional 419 tests were taken from there.
Translator's Note:
In our case (when using Django version 1.6.7), the previous paragraph is somewhat outdated: only one test will start - the one we created. The output of the command will be as indicated below.
(venv:tutorial)$ python manage.py test contacts Creating test database for alias 'default'... . ---------------------------------------------------------------------- Ran 1 tests in 0.001s OK Destroying test database for alias 'default'... (venv:tutorial)$
Creating test database
and Destroying test database
. Some tests require access to the database, and since we don’t want to interfere with test data with “real” (for various reasons, not the least of which is predetermination), Django helpfully creates a test base for us before running the tests. Essentially, a new database is created, and then syncdb
started for it. If the test class is a descendant of the TestCase
class (like ours), Django will also reset the data to default values ​​after running each test, so the changes in one of the tests will not affect the others.
syncdb
creates tables in your database from models. In Django version 1.7 and higher, instead of the syncdb
you must first use the makemigrations
command — to create migrations, and then the migrate
command — to make changes to the database.test
control command runs unit tests.Translator's Note:
In order to test our, still empty, application, you need to run the following command:
(venv:tutorial)$ python ./manage.py runserver 0.0.0.0:8080
This will launch the built-in server, the functionality of which Django graciously provides us. The parameters after therunserver
indicate the ip-address and port that the server will listen to. In our case, the server will receive requests from all ip-addresses when accessing port 8080.
I use to develop a home server with an internal IP of 192.168.1.51. So in order to see the result of the development server in the browser, I go to http://192.168.1.51:8080/ . You must substitute the address of your server.
Source: https://habr.com/ru/post/240463/