Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Getting Started with Django 1.6

Getting started with a project is a critical time when the choices made can have long-term consequences. There are a number of tutorials on how to get started with the Django framework, but they do not really tell how Django works in a professional environment. Starting with this little planning, you will go a long way, which in the future will make your life easier.

By the end of this article, you will have:

  • Completely functional project Django 1.6
  • All resources in the project are in the version control system (git or Mercurial)
  • Automatic return to the previous state and unit testing (using the unittest library)
  • The environment for independent installation of your project (using virtualenv)
  • Automatic deployment and testing (using Fabric)
  • Automatic database migration (using South)
  • Develop a workflow that scales according to your site.

None of these steps, except, perhaps, the first, is not contained in the official training manual. But they should be there. If you are looking for a new Django 1.6 project ready for production, then you can no longer search, but read on.

Before starting work.

It assumes a practical knowledge of Python. Also some experience with Django can be very useful, but it is not strictly necessary. You will need git or Mercurial for version control. It’s all!

Preparing for installation.

I’m assuming that you already have Python installed. If you do not have Python installed, go to python.org and find installation instructions for your operating system. I ran the installation of 64-bit Arch Server from Linode, which I am very pleased with.

So what is the first step? In the Django installation, right? Not certainly in that way. One common problem with installing packages directly to your current domain on the site is that if you have more than one project or Python is used for anything other than Django, then you may encounter a compatibility problem between your applications and installed packages . For this reason, we will use virtualenv and an excellent extension virtualenvwrapperto manage the installation of our Django.

This is the general recommended procedure for all Python and Django users. If you use pipto install packages (and I see no reason why you should not use it), then you can get it virtualenvand virtualenvwrapperjust install the latest one.

pip install virtualenvwrapper

After the packages are installed, add the following lines to your shell startup file ( .zshrc, .bashrc, .profile, etc ).

export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

Reboot your shell startup file (for example source .zshrc).

Create a new environment.

Creating a virtual environment is easy. Just type:

mkvirtualenv django_project

where django_project is the name that you gave to your project.

You will notice that several things will happen at once:

  • The beginning of the path to your shell was added (django_project)
  • Setuptools and pip were automatically installed (in a virtual shell)

This is an extremely useful part of virtualenvwrapper: it automatically prepares your environment in such a way that you can immediately start installing packages with pip. The part django_projectreminds you that you are using virtualenv instead of the one installed in your Python system. To exit the virtual environment, just type deactivate. When you want to resume working on your project, just type workon django_project. Note that unlike conventional virtualenv, it does not matter where you enter these commands.

Installing Django

“Wait, installing Django? I already installed Django! “. Fantastic. You are not going to use it. Instead, we will use virtualenvthat will not create a mess of packages in the system, because all packages necessary for the project will be installed in the virtual environment of the project). To install Django in virtualenv, just type:

~~~ {.bash} pip install django


You will need to download the latest version of Django, which will be installed in the shell ** virtualenv **. You can confirm this with the following actions:
~~~{.sh}
which django-admin.py

You should see a path that should point to your directory $HOME/.virtualenvs/. If it does not specify, you can enable virtualenv by running the command workon django_project.

Creating a django project

Before we start working with the project directly, we need to talk a little. I consulted on a number of Django / Python projects and spoke with numerous developers in the last few years. In the overwhelming majority of cases, there are many problems and difficulties for those who do not use any version control system. This may seem incredible (given the popularity of GitHub), but some developers simply never worked with the version control system. Others believe that, since, “This is a small project,” then there is no need. ERROR.

NO ONE OF THE TOOLS LISTED HEREIN WILL BE MORE USEFUL THAN USING THE VERSION CONTROL SYSTEM.

I used to mention git (D) VCS. However, this project, being in Python, can use Mercurial, which is a worthy alternative, based on Python. Both VCS are quite popular, and teaching materials can be easily found on the Internet. Make sure that you have git or Mercurial installed. Both are certainly available through your distribution and operating system package.

If you plan to use git, GitHub is an obvious choice for storing remote storage. When working with Mercurial, Bitbucket is an excellent choice (it also supports git, so you can use it anyway).

(Home) Managing Your Environment

While we have not done anything yet, we know that we want everything to be under control. We have several cases that we are going to do: our code itself (including templates, etc.) and auxiliary files such as database fixtures, South migration (more on this later), and the requirements.txt file in which All the packages for your project are listed and they will be automatically installed with their dependencies (which saves us from manually installing packages).

Let’s move on and create a project catalog. Use the startproject command from django-admin.py to create it.

django-admin.py startproject django_project

We’ll see a simple directory: django_project . Going into django_project catalog, we will see another folder django_project, which contains: settings.pyurls.py, and wsgi.py. At the same level as the second django_projectdirectory , there is a file manage.py.

Projects against applications

You might be wondering why else in Django 1.4 the startproject command was added along with the already existing startapp command. The answer lies in the difference between Django “projects” and Django “apps”. In short, a project is the entire website or application. “App” is a small, (hopefully) standalone Django application that can be used in any Django project. If you are making an application for blogs, called “SuperBlogger”, then “SuperBlogger” is your Django project. If “SuperBlogger” supports polls of readers, then “polls” would be the Django application used in “SuperBlogger”. The idea is that your “polls” application should be used in any Django project that needs polls, not just in “SuperBlogger”. The project is a collection of different applications along with the project itself. Applications can be used in several projects.

An application architecture based on the principle of weak coupling and writing your applications as stand-alone entities, prevents incorrect design decisions and errors in your project that directly affect your application. It also means that if you wanted, you could pass on the development of any of your applications to others, without affecting or changing your main project. Like many things in software development, this requires very little effort, but it will pay off quite later.

Configuring our repository

Since there are already some files in our project (of course, only a couple of “raw scripts” and empty configuration files), now is the most suitable time to initialize our project to the version control system. Here’s how to do this in git and mercurial.

git :

git init

This will create a git repository in the current directory. Then put all the files in the git repository.

~~~ {.sh} git add.


Now we will commit them:
~~~{.sh}
git commit -m 'Initial commit of django_project'

Mercurial :

~~~ {.sh} hg init


This will create a Mercurial repository in the current directory.
~~~{.sh}
hg add django_project

Now we’ll add them to our new repository:

~~~ {.sh} hg commit -m ‘Initial commit of django_project’


If you plan to use services such as GitHub or Bitbucket, now is the time to do `push`.
## Use South to migrate the database.
One of the most unpleasant aspects of Django is the management of changes in models and associated changes in the database. With South, you can modify the models in the application without writing a specific code for the database. Changes in your models will be detected and automatically made in the database via the migration file that South will create. This allows you to perform a migration to make new changes in it, but you can also roll back to cancel a change or a series of changes. This will greatly simplify your life, it's amazing, but it's a distro that is not included in Django by default.
### When you start using South
In past articles, I recommended that you use South from the very beginning of your project. For relatively simple projects, it's fine. But if, you have many models that change as quickly as your prototype, then it's not yet time to use the South. Then just delete and recreate the database when necessary. You can write scripts to populate the database with some test data and edit them if necessary. However, after your models stop changing, you need to resort to South help as soon as possible. This can be done like this: `./manage.py convert_to_south `.
### Installation and Configuration
Also on our virtualenv install South as follows:
~~~bash
pip install south

We customize our Southadding it in the settings.pyINSTALLED_APPS file . We add that now you also need to configure the database for the project, then run it . You will be prompted for the superuser name and password. More importantly, you need South to set up a database with tables.python manage.py syncdb

You might have noticed that we just ran syncdb without adding the application to the project (without adding it to INSTALLED_APPS). We do this in order to install South in the beginning. All migrations in our own applications will have to be carried out with the help of the South, including the initial migrations.

Since we have just made some pretty big changes, now is the time to fix these changes. You should save your project as often as possible, because with frequent saving you will have more freedom to choose a particular point of recovery, if something goes wrong.

To keep or “fix” the project at one stage or another, let’s see what has been changed.

git

~~~ {.sh} $ git status

On branch master

Changes not staged for commit:

(use “git add … “to update what will be committed)

(use “git checkout – … “to discard changes in working directory)

#

modified: django_project / settings.py

#

Untracked files:

(use “git add … “to include in what will be committed)

#

django_project / .settings.py.swp

django_project / init .pyc

django_project / settings.pyc


**Mercurial**

~~~{.sh}
$ hg status

M django_project/django_project/settings.py
? django_project/django_project/.settings.py.swp
? django_project/django_project/__init__.pyc
? django_project/django_project/settings.pyc

In both git and Mercurial, you may notice that there are files that you never wanted to capture, python files such as .pyc and vim swap .swp files above. To ignore these files, create a .gitignore or .hgignore file in the directory of your main project and add a shell template to reflect in it the files you do not want to save.

For example, the contents of this file can be:

~~~ {.sh} .pyc. swp


Before we do this, we have one more place to write: our installed Python packages. We want to keep track of the Python packages that we use in the project and that we could easily recreate our environment on the product server. Fortunately, there is a command in `pip` that does what we need.
~~~bash
pip freeze > requirements.txt

I sent the output to a file called requirements.txt, which we will add to the version control system, so we always have an updated list of what is used in the packages.

(git/hg) add django_project/settings.py requirements.txt
(git/hg) commit -m 'Added South for database migrations'

New Style Settings

One of the main patterns for the settings.py file is moving it to another directory, for example confor config. But in this case you will have to make a small change in manage.py to coordinate the move.

With settings.py and INSTALLED_APPS you can quickly get bogged down in third-party packages in common Django applications and in your own applications. I would like to divide INSTALLED_APPS into three categories:

  • DEFAULT_APPS: Django framework applications
  • THIRD_PARTY_APPS: for example, South
  • LOCAL_APPS: The apps you create

This method makes it much easier to understand which non-core applications you use and which ones are crammed with unnecessary information.

Just remember, after all, there is a line similar to the following:

~~~ {.python} INSTALLED_APPS = DEFAULT_APPS + LOCAL_APPS + THIRD_PARTY_APPS


Otherwise, Django will complain that there are no definitions INSTALLED_APPS.
## Creating our application
Use manage.py to create the application in the usual way (python manage.py startapp myapp) and add it to INSTALLED_APPS. In addition, make manage.py run (`chmod + x manage.py`), so you can just type ./manage.py . Honestly, very few developers do it. And all my life I can not understand why.
The first thing we do before adding models, let's say South, is that we want to manage changes in our models with the help of migrations:
~~~bash
python manage.py schemamigration myapp --initial

This command will create a migration file that you can use to make changes to our models (if they will be) and to the database, without having to completely delete and restore it. This will also allow us to undo the changes if they turn sideways for us. We will use migration files to migrate changes to the database (even if they are not) using:

python manage.py migrate myapp

South is smart enough to know where to find the migration files, and also to remember which migrations we made the last time. You can specify individual migration files, but usually, this is not necessary. When we make changes to our model, we ask South to create a migration using:

python manage.py schemamigration myapp --auto

This will check the models in myapp and automatically add, delete, or modify the tables in the database. Changes can be applied to the database using the migrate command, as described above.

Our area of ​​development

It is necessary to develop a good habit of writing and testing the code separately from your working files, this is necessary, for example, in order not to render your site in an inoperative state from the encoding error when adding new functionality. In git and Mercurial, this is very easy to do. Just create the directory somewhere else, not where django_project is installed . You can create a new virtual environment for the development environment devwith your own directory, in this environment, you can also evolve and develop (using the dev branch). And the current django_project is used as the emulator of the product server (using the master branch) and roll out the updates there, before sending it to the real product server.

In the new development directory (dev), copy your current project using git or Mercurial:

~~~ {.sh} (git / hg) clone / path / to / my / project /


Both tools will create an exact copy of the entire repository. All changes, branches and history will be available here. From now on, you must work from the development directory.
Using branching in git and Mercurial, you can create branches for a new functional without affecting the main code.
Here's how to do this for each tool:
**git**

~~~{.sh}
git checkout -b 

Which will also create a new branch and check it. Almost all your development areas (dev, prod) should work with branches, for example, the branch mastersimulates a “product version of the site” (or “or the current version of the site”), the master can also be used for recovery at any time.

(Mercurial)

hg branch branchname>

Using Fabric for Deployment

So, we have everything you need for an application on Django. What are we going to do now? Fabric. Fabric can be used for various purposes, but it is really necessary for deployment.

~~~ {.sh} pip install fabric


Fabric expects a file named ** fabfile.py ** that identifies all the actions that we can take. Let's create it now. Place fabfile.py in the root directory of your project.
~~~{.python}
from fabric.api import local

def prepare_deployment(branch_name):
    local('python manage.py test django_project')
    local('git add -p && git commit') # or local('hg add && hg commit')

This will help run the tests and commit changes, but only if your tests pass. At this point, just pull on your product server and the code will begin to unfold. Let’s add something else for the actual deployment. Add this to your fabfile.py:

~~~ {.python} from fabric.api import lcd, local

def deploy (): with lcd (‘/ path / to / my / prod / area /’):

    # git...
    local('git pull /my/path/to/dev/area/')

    # Mercurial...
    local('hg pull /my/path/to/dev/area/')
    local('hg update')

    local('python manage.py migrate myapp')
    local('python manage.py test myapp')
    local('/my/command/to/restart/webserver')

This method will take changes from the master branch of the repository, run the migrations that you made, run your tests, and reload the web server. All in one simple command that runs from the command line. If one of these steps fails, the script will stop and report what happened. After you correct the problem, there is no need to start the steps manually. Since they are identical, you can simply execute the command repeatedly, and everything will be fine.
Note that the above code assumes that you are running on the same machine as it is deployed. If it is not, the file will be almost the same, but it will use the Fabric run function instead of local. For more details, see the Fabric documentation.
Now we have our created fabfile.py, how do we apply it? Very simple. Just run:
~~~{.sh}
fab prepare_deployment
fab deploy

Configuring unit tests

If you know anything about me, then for sure, it will be that I adore automatic tests. Too many Django projects are created without any tests. This is another of those things that you should spend a little time on, but it will pay off in the future. If you’ve ever debugged an application using the print statement, having the correct tests for that location might have freed you a lot of time. For Django, the python of the unittest module is enough. Below is a small example of testing on one application:

~~~ {.python} import datetime

from django.test import TestCase from myapp.models import Post

class BlogPostTestCase (TestCase): def setUp (self): Post.objects.create (id = 1, title = ‘Starting a Django 1.6 Project the Right Way’, date = datetime.datetime.now (), category = ‘Django’ ) Post.objects.create (id = 2, title = ‘Python \’ s Hardest Problem ‘, date = datetime.datetime.now (), category =’ Python ‘)

def test_posts_have_category(self):
    """Animals that can speak are correctly identified"""
    first_post = Post.objects.get(id=1)
    second_post = Post.objects.get(id=2)
    self.assertEqual(first_post.category, 'Django')
    self.assertEqual(second_post.category, 'Python')


You can put this code in a file named `test_  .py` and place it where the application directory you want to test is also located. To run the tests, simply type `./manage.py test `. The Fabfile that we created already knows how to run tests before deployment, so there's no need to make any further changes.
Enjoy the new Django app
That's all! You are ready to begin your actual development. Now the fun begins. Just remember: commit often, test everything, and do not need to write code that you can not test.

The post Getting Started with Django 1.6 appeared first on Techy360.



This post first appeared on TECHY360 - Gadgets Reviews Tutorials Interview Questions, please read the originial post: here

Share the post

Getting Started with Django 1.6

×

Subscribe to Techy360 - Gadgets Reviews Tutorials Interview Questions

Get updates delivered right to your inbox!

Thank you for your subscription

×