Getting Started with PyCharm as a Django Development Tool
Welcome to PyCharm! This Quick Start Guide aims to walk you through your first Django project with PyCharm. As an example, we'll take the polls application from Django — thus you will be able to try hand-on all the conveniences provided by PyCharm.
In this document:
Before you start...
Make sure that you have Python version from 2.4 to 2.7, and Django framework properly installed on your machine. See download and installation instructions here and here.
Creating/opening your Django application
Let's start from the very beginning, namely creating a Django application from scratch. Creating a new project is most easy: choose File | New Project on the main menu.
PyCharm's New Project wizard spares you from some tedious and error-prone work. PyCharm will create the proper Django application structure, provide the necessary import statements, add application to the list of installed applications, if necessary, uncomment lines for site administration and create a directory for the Django templates.
On the first page, enter project name and select its type — Django application. Next, enter Django project name, choose Python interpreter you want to use, and folder for the templates. If you want to create a Django application immediately, specify its name. In our case, this name is polls.
We also want to enable Django admin, and select the admin check box. Note that you can create a project without an application, and add it later.
Next, specify how you want your new project to be opened: in a new window, or added to some previously opened project.
PyCharm executes the startproject task of the django-admin.py utility, and produces the following structure:
Now, when the project stub is ready, let's do some fine tuning. Open for editing the settings.py file.
To do it, select the file in the Project tool window, and press F4F4.
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⌘F, and in the search field start typing the string you are looking for:
Let's change the variable value:
- 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.
Note that you can use basic code completion ( Ctrl+Space⌃Space) here:
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⌥R, and enter task name in the pop-up frame:
If everything is done properly, the console will show something like:
Note that you can use the other databases. In this case, you will need to install the required database management systems and libraries, have the database running on your machine, and also specify your authentication parameters.
By the way, if you want to continue developing an existing Django application and see how nice is working
on it in PyCharm, choose
File | Open Directory on the main menu. Find the folder that contains your project
source code, select it and open.
Creating models
Let's begin with defining models. Open for editing the models.py file of your application
(select the file in the Project tool window, and press F4F4). By default, it only contains the import statement.
We'll enter the model classes:
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()
While you type, you have certainly paid attention to the syntax and error highlighting. Besides that, use the code completion ( Ctrl+Space⌃Space) on actually every stage of coding — PyCharm will smartly suggest the names of classes, methods, or fields, depending on the context:
Then, we need to create tables for the new model. For this purpose, we'll use the magic Ctrl+Alt+R⌥R shortcut twice:
- First, select sql from the suggestion list, and choose the desired application name. This command generates SQL statements for both classes of the polls application:
- Second, select syncdb from the suggestion list to create tables, and see the following results in the console:
Performing administration 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⌃N),
and enter the following code:
from MyDjangoApp.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)
Next, we are 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 whole URL in the address bar, but with PyCharm there is an easier way: use the pre-configured Django server run configuration:
It is recommended to give it a name (in our case this is myapp), enable running the application in your default browser (select the Run browser check box), and specify the page of our site to be opened by default (http://127.0.0.1:8080/admin/):
Now, to launch the application, press Shirt+F10⇧F10, or click
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.
Creating views
We are now going to create views for our application: let it have the pages "archive", "details", "results",
and the "votes" action. First of all, we have to add patterns for the new pages to the urls.py file.
Open this file for editing (select this file in the Project tool window and press F4F4),
and add patterns:
from django.conf.urls.defaults import patterns, include
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^polls/$', 'MyDjangoApp.polls.views.index'),
(r'^polls/(?P<poll_id>\d+)/$', 'MyDjangoApp.polls.views.detail'),
(r'^polls/(?P<poll_id>\d+)/results/$', 'MyDjangoApp.polls.views.results'),
(r'^polls/(?P<poll_id>\d+)/vote/$', 'MyDjangoApp.polls.views.vote'),
(r'^admin/', include(admin.site.urls)),
)
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, a yellow light bulb 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⌥↩.
Clicking the Create Django view method option results in creating a view method in the views.py file, and the corresponding template file:
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 the view method to its template. Having created all the required views methods and templates by means of the quick fix, let's fill them with the suitable code.
Open for editing the index.html file, 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⌃Space to show the list of suggested keywords:
The next invocation of code completion gives the available variables:
When it comes to typing HTML tags, PyCharm is ready to help you again:
- Ctrl+Space⌃Space code completion shows the list of available tags.
- When you type the opening angle bracket, the matching closing tag is generated automatically.
So, you fill your template step by step, and finally get something like the following examples (index.html and detail.html files), with syntax highlighting:
Here we are!
Let's check the list of available polls and the details for a particular poll. 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/:
Click any poll to view its details:
This brief tutorial is over. You have successfully created and launched a simple Django application — congrats!
