Creating and managing Django projectprof

What this tutorial is about?

Tutorial explains how to create and run Django projects with PyCharm and also covers Project tool window and navigation.

What this tutorial is not about?

It does not teach you Python and Django.

Before you start

Make sure that:

  • You are working with PyCharm Professional Edition 3.0 or higher. It can be downloaded here.
  • At least one Python interpreter, version from 2.4 to 3.3 is properly installed on your computer. You can download an interpreter from this page.

This tutorial has been created with the following assumptions:

  • Django 1.6.5
  • Default Windows keymap. If you are using another keymap, the keyboard shortcuts will be different.
  • The example used in this tutorial is similar to the one used in Django documentation.

Creating a new project

Actually, all new projects are created same way: by clicking the Create New Project button in the Quick Start area of the Welcome screen.

If you have an already opened project, create a new one by choosing File → New Project.... Then, in the Create New Project dialog, specify the project name, select its type and the Python interpreter to be used for this project (remember, having at least one Python interpreter is one of the prerequisites of this tutorial!):

screenshots/create_new_project.png

Click OK - the project per se is ready.

It means that the directory with the project name is created in the specified location, and contains .idea directory with the project settings.

For an empty project, the process of creating a new project is over, and you can proceed with developing your pure Python application. As for the other supported frameworks, you are just in the middle... Depending on the selected project type, PyCharm suggests to enter additional, framework-specific settings.

In this example, let's create and explore a Django application.

Creating a Django project

So, in the Create New Project dialog we've selected the project type Django - note that PyCharm suggests to install the Django framework, if it is missing from the selected interpreter (which, by the ways, is rather time-consuming).

Next, let's define the Django-specific project settings:

screenshots/create_project_django_1..png

So... click OK, and the stub Django project is ready.

Exploring project structure

As mentioned above, basically, the stub project is ready. It contains framework-specific files and directories. Same happens when you create a project of any supported type, be it Pyramid, or Google App Engine.

Let's see how the structure of the new project is visible in the Project tool window.

Project view of the Project tool window

This view is displayed by default. It shows the Django-specific project structure polls and MyDjangoApp directories; also, you see the manage.py and settings.py files.

You cannot see the .idea directory in this view:

screenshots/django_project_view.png

Project Files view of the Project tool window

If for some reasons you would like to see contents of the .idea directory, choose the view Project Files: as you see, this view shows same directories and files, plus .idea directory, since is located under the project root.

screenshots/django_project_files_view.png

By now, let's return to the Project view.

What do we see in the Project view?

  • untitled directory is a container for your project. In the Project view it is denoted with bold font.
  • manage.py: This is a command-line utility that lets you interact with your Django project. Refer to the product documentation for details.
  • The nested directory MyDjangoApp is the actual Python package for your project.
  • MyDjangoApp/_init_.py: This empty file tells Python that this directory should be considered a Python package.
  • MyDjangoApp/settings.py: This file contains configuration for your Django project.
  • MyDjangoApp/urls.py: This file contains the URL declarations for your Django project.
  • MyDjangoApp/wsgi.py: This file defines an entry-point for WSGI-compatible web servers to serve your project. See How to deploy with WSGI for more details.
  • Finally, the nested directory polls contains all the files required for developing a Django application (at this moment, these files are empty):
    • Again, polls/_init_.py: tells Python that this directory should be considered a Python package.
    • polls/models.py: In this file, we'll create models for our application.
    • polls/views.py: In this file, we'll create views.
  • templates directory is by now empty. It should contain the template files.

Note that you can create as many Django applications as needed. To add an application to a project, run the startapp task of the manage.py utility (Tools→Run manage.py task - startapp on the main menu).

Configuring the database

Now, when the project stub is ready, let's do some fine tuning. Open for editing settings.py. To do it, select the file in the Project tool window, and press F4. The file is opened in its own tab in the editor.

Specify which database you are going to use in your application. For this purpose, find the DATABASES variable: click Ctrl+F, and in the search field start typing the string you are looking for. Then, in the 'ENGINE' line, add the name of your database management system after dot (you can use any one specified after comment, but for the beginning we'll start with sqlite3.)

In the 'NAME' line, enter the name of the desired database, even though it doesn't yet exist.

screenshots/database.png

Launching the Django server

Since we've prudently chosen sqlite3, we don't need to define the other values (user credentials, port and host). Let's now check whether our settings are correct. This can be done most easily ? just launch the runserver task of the manage.py utility: press Ctrl+Alt+R, and enter task name in the pop-up frame:

screenshots/django_runserver.png

Creating models

Next, open for editing the file models.py, and note that import statement is already there. Then type the following code:

from django.db import models


class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField() 

Actually, you can just copy-paste, but typing is advisable - it helps you see the powerful PyCharm's code completion in action:

screenshots/django_code_completion.png

Creating database

We have to create tables for the new model. For this purpose, we'll use the magic Ctrl+Alt+R shortcut twice:

  • First, select sql from the suggestion list, and choose the desired application name:
screenshots/django_sql_choose_app.png

This command generates SQL statements for both classes of our application:

screenshots/django_sql_tables_created.png
  • Second, select syncdb from the suggestion list to create tables, and see the following results in the console:
screenshots/django_syncdb.png?version=2&modificationDate=1403274184000

Performing administrative functions

Since we've decided to enable site administration, PyCharm has already uncommented the corresponding lines in the urls.py file.

However, we need to enable editing functionality for the admin site. To do that, create admin.py file in the polls directory (Alt+Ins), and enter the following code:

from polls.models import Poll, Choice
from django.contrib import admin


class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 3


class PollAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['question']}),
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']})
    ]
    inlines = [ChoiceInline]

admin.site.register(Poll, PollAdmin) 

Again pay attention to the code completion:

screenshots/django_code_completion_1.png?version=2&modificationDate=1403275203000

Preparing run/debug configuration

We are now ready to go to the admin page and create some polls. Sure, it is quite possible to run the Django server, then go to your browser, and type the entire URL in the address bar, but with PyCharm there is an easier way: use the pre-configured Django server run configuration with some slight modifications.
To open this run/debug configuration for editing, on the main toolbar, click the run/debug configurations selector, and then choose Edit Configuration (or choose Run→Edit Configurations on the main menu):

screenshots/django_edit_run_config.png?version=2&modificationDate=1403521871000

In the Run/Dug Configuration dialog box, give this run/debug configuration a name (here it is myapp), enable running the application in the default browser (select the check box Run browser) and specify the page of our site to be opened by default:

screenshots/django_run_config.png?version=1&modificationDate=1403613206000

Launching the admin site

Now, to launch the application, press Shift+F10, or click screenshots/run.png?version=1&modificationDate=1403263710000 on the main toolbar to open the standard Django's site administration page, where you have to log in. Then you can create polls and fill them out with questions and votes:

screenshots/django_admin_site.png?version=2&modificationDate=1403275332000

Creating views

We are now going to create views for our application: let it have the pages "index", "details", "results", and "votes". First of all, we have to add patterns for the new pages to the file urls.py. Open this file for editing (select this file in the Project tool window and press F4), and add patterns:

(r'^polls/$', 'polls.views.index'),
(r'^polls/(?P<poll_id>\d+)/$', 'polls.views.details'),
(r'^polls/(?P<poll_id>\d+)/results/$', 'polls.views.results'),
(r'^polls/(?P<poll_id>\d+)/vote/$', 'polls.views.vote'), 

These patterns refer to the views, which do not yet exist. You can spend some effort to create the view methods and associated templates manually, but it is much easier to use PyCharm's assistance: as you hover your mouse pointer over an unresolved reference (which is, by the way, highlighted), a yellow light bulb screenshots/yellowLightBulb.png?version=1&modificationDate=1403265658000 appears, which means that a quick fix is suggested. To show this quick fix, click the bulb, or, with the caret at the view name, just press Alt+Enter:

screenshots/django_create_view_method.png?version=2&modificationDate=1403275911000

Clicking the Create Django view method option results in creating a view method in the views.py file, and the corresponding template file in the specified location.

What do we see now?

  • First, the templates directory, marked screenshots/folder_purple.png?version=1&modificationDate=1403267271000, is not empty any more. It contains the stub templates we've created.
  • Second, the file views.py now contains the stub view methods.
screenshots/django_view_and_template.png

Besides the view methods, PyCharm generates the import statement that enables you to use render_to_response.

Note also the icon in the left gutter next to the name of each view method ? you can use it to navigate from a view method to its template. Having created all the required views and templates by means of the Create template<name> quick fix, let's fill them with some suitable code.

For example, we'd like to see the list of available polls. So, make sure that the file views.py is opened for editing, and type the following code:

def index(request):
    poll_list = Poll.objects.all()
    t = loader.get_template('index.html')
    c = Context({
        'poll_list': poll_list,
    })
    return HttpResponse(t.render(c)) 

PyCharm suggests a quick fix to add the missing imports statements:

screenshots/django_import_quick_fix.png?version=1&modificationDate=1403603620000

So at the end you should see the following:

from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response
from django.template import loader, Context
from polls.models import Poll

def index(request):
    poll_list = Poll.objects.all()
    t = loader.get_template('index.html')
    c = Context({
        'poll_list': poll_list,
    })
    return HttpResponse(t.render(c)) 

Creating templates

Let's fill in one of the templates with some meaningful code. Open for editing the file index.html, and start typing the template code. First thing you will notice immediately, is the automatic pair braces completion: when you type {%, PyCharm adds the matching closing characters, and the caret rests in the next typing position. Here you can press Ctrl+Space to show the list of suggested keywords:

screenshots/django_template_edit.png

When it comes to typing HTML tags, PyCharm is ready to help you again:

  • Ctrl+Space code completion shows the list of available tags.
  • When you type the opening angle bracket, the matching closing bracket is generated automatically.

So, you fill your template step by step, and finally get something like the following example (index.html and details.html), with syntax highlighting:

screenshots/django_template_code.png

Here we are!

Let's check the list of available polls. Our admin site is already running, and the easiest way to visit the page that contains the list of polls (the index page), is to specify its URL in the address bar of the browser ? instead of /admin/, type /polls/:

screenshots/result.png?version=1&modificationDate=1403606929000

Click any poll to view its details:

screenshots/result1.png?version=1&modificationDate=1403610456000

Summary

This brief tutorial is over. You have successfully created and launched a simple Django application.

Let's repeat what have we done with the help of PyCharm:

  • created a Django project and application
  • launched the Django server
  • configured a database
  • created models, views and templates

Congrats!