Writing your first Django application – Part 1

Let’s learn by example.

Through this tutorial, we will walk you through creating a basic voting application.

It will consist of two parts:

  • A public site for people to view and vote.
  • An administrative site that allows you to add, modify, and delete votes.

We assume that you’ve read about installing Django. You can tell if Django is installed, and which version it is, by typing the command (prefixed with $) at the command prompt.

 /  

$ python -m django --version
Copy the code

If this command outputs a version number, youll already have Django installed. If you get an error saying “No module named Django”, you haven’t installed it yet.

This tutorial was written for Django 2.1, which supports Python 3.5 and later. If Django versions don’t match, you can use the version switcher at the bottom right of the page to switch to the tutorial for your version, or to update to the latest version. If you are using an older version of Python, which version of Python should I use with Django? Find a suitable Django version.

You can check out the documentation how to Install Django for instructions and advice on removing old versions and installing new ones.

Where to get help:

If you’re having trouble reading or practicing this tutorial, please send a message to Django-users or join # Django on irc.freenode.net to communicate with other Django users who may be able to help you.

Create a project

If this is your first time using Django, you will need some initial Settings. That is, you need to configure a Django project with some automatically generated code — that is, the set of Settings required by a Django project instance, including database configuration, Django configuration, and application configuration.

Open the command line, CD to a directory where you want to put your code, and run the following command:

 /  

$ django-admin startproject mysite
Copy the code

This line of code will create a mysite directory in the current directory. If the command fails, it may help to look at the problems you have with running Django-admin.

annotations

You should avoid using Python or Django internal reserved words to name your projects. Specifically, you should avoid names like Django (which conflicts with Django itself) or test (which conflicts with Python’s built-in components).

Where do I put my code?

If you’ve ever been a native PHP programmer (without using modern frameworks), you’ve probably been used to putting code in the document root of a Web server (such as /var/www). You don’t need to do this when using Django. It is not a good idea to put all Python code in the root directory of the Web server because it is risky. For example, it increases the likelihood that people will see your code on the site. This is not good for website security.

Put your code somewhere other than the document root, such as /home/mycode.

Let’s see what startProject creates:

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py
Copy the code

These directories and files are useful for:

  • The outermost :file: mysite/ root directory is just a container for your project. Django doesnt care what its name is. You can rename it to anything you like.
  • manage.pyA command line tool that lets you manage Django projects in a variety of ways. You can readdjango-admin and manage.pyGet all themanage.pyThe details.
  • It’s on the insidemysite/The directory contains your project, which is a pure Python package. Its name is the name of the Python package you need when you reference anything inside it. (e.g.,mysite.urls).
  • mysite/__init__.py: an empty file that tells Python that the directory should be considered a Python package. If you are new to Python, read the official documentationLearn more about packages.
  • mysite/settings.py: Configuration file for a Django project. If you want to know how this file works, check it outDjango settingsGet the details.
  • mysite/urls.pyThe URL declaration for your Django project, like the “directory” for your web site. readingURL schedulerDocument to get more information about urls.
  • mysite/wsgi.py: as an entry point for your project to run on a WSGi-compatible Web server. readingHow do I deploy with WSGIFor more details.

Simple server for development

Let’s verify that your Django project has been successfully created. If your current directory is not the outer mysite directory, please switch to it and run the following command:

 /  

$ python manage.py runserver
Copy the code

You should see the following output:

Performing system checks... System check identified no issues (0 silenced). You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. Django Version 2.1, February 28, 2019-15:50:53, Using Settings 'mysite. Settings' Starting development server at http://127.0.0.1:8000/ Quit the server with control-c.Copy the code

annotations

Ignore warnings about not applying the latest database migration, and we’ll deal with the database later.

What you’ve just started is Django’s built-in Easy Server for development, a lightweight Web server written in pure Python. We built this server into Django so that you can quickly develop what you want, because you don’t need to configure a production-level server (like Apache) unless you’re ready to go into production.

Now is a good time to remind you: Do not use this server for anything related to your production environment. This server is designed for development only. (We are experts in Web frameworks, not Web servers.)

Now, the server is running and the browser is at https://127.0.0.1:8000/. You will see a “congratulations” page and the server is up and running with a rocket launch.

Change the port

By default, the runserver command sets the server to listen on port 8000 of the local internal IP.

If you want to change the listening port of the server, use the command line argument. For example, the following command causes the server to listen on port 8080:

 /  

$ python manage.py runserver 8080
Copy the code

If you want to change the IP that the server is listening to, type a new one before the port. For example, to listen for the public IP of all servers (useful if you’re running Vagrant or want to show your work to other computers on the network), use:

 /  

$ python manage.py runserver 0:8000
Copy the code

0 is short for 0.0.0.0. Complete documentation on the development server can be found in the :djamdin: ‘runServer’ reference.

The server runServer is automatically reloaded

The development server reloads Python code for each access request as needed. So you don’t need to restart the server frequently to make changes to the code take effect. However, some actions, such as adding new files, will not trigger an automatic reload and you will have to manually restart the server yourself.

Creating the Poll app

Now that your development environment — the “project” — is configured, you can get to work.

In Django, every application is a Python package and follows the same conventions. Django comes with a tool that will help you generate your application’s basic directory structure so you can focus on writing code instead of creating directories.

Project VS Application

What’s the difference between a project and an application? An application is a web application that does just one thing — like a blogging system, or a database of public records, or a simple voting program. A project is a collection of configurations and applications used by a site. Projects can contain many applications. Applications can be used by many projects.

Your application can be stored in any path defined in Python Path. In this tutorial, we will create the voting application in your manage.py peer directory. This way it can be imported as a top-level module, rather than a submodule of mysite.

Make sure you are in the same directory as manage.py and run this command to create an application:

 /  

$ python manage.py startapp polls
Copy the code

This will create a directory of polls, which looks like this:

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py
Copy the code

This directory structure contains the entire content of the poll application.

Write the first view

Let’s start writing our first view. Open polls/views.py and type in the following Python code:

Polls/views. Py ¶

from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")
Copy the code

This is the simplest view in Django. To see the effect, we need to map a URL to it — that’s why we need URLconf.

To create URLconf, create a new urls.py file in the Polls directory. Your app directory should now look like this:

polls/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    urls.py
    views.py
Copy the code

In the polls/urls.py, type the following code:

Polls/urls. Py ¶

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
Copy the code

The next step is to specify the polls. Urls module we created in the root URLconf file. Insert an include() in the list of urlpatterns in the mysite/urls.py file as follows:

Mysite/urls. Py ¶

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]
Copy the code

The function include() allows references to other URLconfs. Whenever Django encounters :func: ~django.urls.include, it truncates the portion of the URL that matches that item and sends the remaining string to the URLconf for further processing.

We designed Include () with the idea that it can be plugged and played. Because polls have their own URLconf(polls/urls.py), they can be placed in “/polls/”, “/fun_polls/”, “/content/polls/”, or any other path, and the app will work.

When to use include()

You should always use include() when including other URL patterns, with the exception of admin.site.urls.

You’ve now added the index view to the URLconf. To verify that this is working, run the following command:

 /  

$ python manage.py runserver
Copy the code

Use your browser to http://localhost:8000/polls/, You should be able to see “Hello, world. You ‘r e at the polls index.”, this is what You defined in the index view.

No page found?

If you get an error page here, check whether you are visiting http://localhost:8000/polls/ and should not be http://localhost:8000/.

The function path() takes four arguments, two mandatory: route and view, and two optional arguments: kwargs and name. Now, it’s time to look at what these parameters mean.

path()Parameters:route

A route is a guideline (similar to a regular expression) for matching urls. When Django responds to a request, it starts with the first item in urlPatterns and matches the items in the list in sequence until it finds a match.

These guidelines do not match GET and POST parameters or domain names. URLconf, for example, in dealing with a request to https://www.example.com/myapp/, it will try to match the myapp /. When processing requests https://www.example.com/myapp/?page=3, also can only try to match the myapp /.

path()Parameters:view

When Django finds a match, it calls this particular view function and passes in an HttpRequest object as the first argument. The “captured” argument is passed in as a keyword argument. We’ll give you an example later.

path()Parameters:kwargs

Any keyword argument can be passed as a dictionary to the target view function. This feature will not be used in this tutorial.

path()Parameters:name

Naming your URL lets you uniquely reference it anywhere in Django, especially in templates. This useful feature allows you to globally modify a URL schema by changing only one file.

Once you understand the basic request and response process, read Part 2 of the tutorial to get started with the database.