Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
Django

The web framework for perfectionists with deadlines.

Documentation

Writing your first Django app, part 1

Let’s learn by example.

Throughout this tutorial, we’ll walk you through the creation of a basicpoll application.

It’ll consist of two parts:

  • A public site that lets people view polls and vote in them.

  • An admin site that lets you add, change, and delete polls.

We’ll assume you haveDjango installed already. You cantell Django is installed and which version by running the following commandin a shell prompt (indicated by the $ prefix):

$python-mdjango--version
...\> py -m django --version

If Django is installed, you should see the version of your installation. If itisn’t, you’ll get an error telling “No module named django”.

This tutorial is written for Django 5.2, which supports Python 3.10 andlater. If the Django version doesn’t match, you can refer to the tutorial foryour version of Django by using the version switcher at the bottom right cornerof this page, or update Django to the newest version. If you’re using an olderversion of Python, checkWhat Python version can I use with Django? to find a compatibleversion of Django.

Where to get help:

If you’re having trouble going through this tutorial, please head over totheGetting Help section of the FAQ.

Creating a project

If this is your first time using Django, you’ll have to take care of someinitial setup. Namely, you’ll need to auto-generate some code that establishes aDjangoproject – a collection of settings for an instance of Django,including database configuration, Django-specific options andapplication-specific settings.

From the command line,cd into a directory where you’d like to store yourcode and create a new directory nameddjangotutorial. (This directory namedoesn’t matter to Django; you can rename it to anything you like.)

$mkdirdjangotutorial
...\>mkdir djangotutorial

Then, run the following command to bootstrap a new Django project:

$django-adminstartprojectmysitedjangotutorial
...\> django-admin startproject mysite djangotutorial

This will create a project calledmysite inside thedjangotutorialdirectory. If it didn’t work, seeProblems running django-admin.

Note

You’ll need to avoid naming projects after built-in Python or Djangocomponents. In particular, this means you should avoid using names likedjango (which will conflict with Django itself) ortest (whichconflicts with a built-in Python package).

Let’s look at whatstartproject created:

djangotutorial/    manage.py    mysite/        __init__.py        settings.py        urls.py        asgi.py        wsgi.py

These files are:

  • manage.py: A command-line utility that lets you interact with thisDjango project in various ways. You can read all the details aboutmanage.py indjango-admin and manage.py.

  • mysite/: A directory that is the actual Python package for yourproject. Its name is the Python package name you’ll need to use to importanything inside it (e.g.mysite.urls).

  • mysite/__init__.py: An empty file that tells Python that thisdirectory should be considered a Python package. If you’re a Python beginner,readmore about packages in the official Python docs.

  • mysite/settings.py: Settings/configuration for this Djangoproject.Django settings will tell you all about how settingswork.

  • mysite/urls.py: The URL declarations for this Django project; a“table of contents” of your Django-powered site. You can read more aboutURLs inURL dispatcher.

  • mysite/asgi.py: An entry-point for ASGI-compatible web servers toserve your project. SeeHow to deploy with ASGI for more details.

  • mysite/wsgi.py: An entry-point for WSGI-compatible web servers toserve your project. SeeHow to deploy with WSGI for more details.

The development server

Let’s verify your Django project works. Change into thedjangotutorialdirectory, if you haven’t already, and run the following commands:

$pythonmanage.pyrunserver
...\> py manage.py runserver

You’ll see the following output on the command line:

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.July 17, 2025 - 15:50:53Django version 5.2, using settings 'mysite.settings'Starting development server athttp://127.0.0.1:8000/Quit the server with CONTROL-C.WARNING: This is a development server. Do not use it in a production setting. Use a production WSGI or ASGI server instead.For more information on production servers see:https://docs.djangoproject.com/en/5.2/howto/deployment/

Note

Ignore the warning about unapplied database migrations for now; we’ll dealwith the database shortly.

Now that the server’s running, visithttp://127.0.0.1:8000/ with your webbrowser. You’ll see a “Congratulations!” page, with a rocket taking off.It worked!

You’ve started the Django development server, a lightweight web server writtenpurely in Python. We’ve included this with Django so you can develop thingsrapidly, without having to deal with configuring a production server – such asApache – until you’re ready for production.

Now’s a good time to note:don’t use this server in anything resembling aproduction environment. It’s intended only for use while developing. (We’re inthe business of making web frameworks, not web servers.)

(To serve the site on a different port, see therunserver reference.)

Automatic reloading ofrunserver

The development server automatically reloads Python code for each requestas needed. You don’t need to restart the server for code changes to takeeffect. However, some actions like adding files don’t trigger a restart,so you’ll have to restart the server in these cases.

Creating the Polls app

Now that your environment – a “project” – is set up, you’re set to startdoing work.

Each application you write in Django consists of a Python package that followsa certain convention. Django comes with a utility that automatically generatesthe basic directory structure of an app, so you can focus on writing coderather than creating directories.

Projects vs. apps

What’s the difference between a project and an app? An app is a webapplication that does something – e.g., a blog system, a database ofpublic records or a small poll app. A project is a collection ofconfiguration and apps for a particular website. A project can containmultiple apps. An app can be in multiple projects.

Your apps can live anywhere in yourPython path. Inthis tutorial, we’ll create our poll app inside thedjangotutorial folder.

To create your app, make sure you’re in the same directory asmanage.pyand type this command:

$pythonmanage.pystartapppolls
...\> py manage.py startapp polls

That’ll create a directorypolls, which is laid out like this:

polls/    __init__.py    admin.py    apps.py    migrations/        __init__.py    models.py    tests.py    views.py

This directory structure will house the poll application.

Write your first view

Let’s write the first view. Open the filepolls/views.pyand put the following Python code in it:

polls/views.py
fromdjango.httpimportHttpResponsedefindex(request):returnHttpResponse("Hello, world. You're at the polls index.")

This is the most basic view possible in Django. To access it in a browser, weneed to map it to a URL - and for this we need to define a URL configuration,or “URLconf” for short. These URL configurations are defined inside eachDjango app, and they are Python files namedurls.py.

To define a URLconf for thepolls app, create a filepolls/urls.pywith the following content:

polls/urls.py
fromdjango.urlsimportpathfrom.importviewsurlpatterns=[path("",views.index,name="index"),]

Your app directory should now look like:

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

The next step is to configure the root URLconf in themysite project toinclude the URLconf defined inpolls.urls. To do this, add an import fordjango.urls.include inmysite/urls.py and insert aninclude() in theurlpatterns list, so you have:

mysite/urls.py
fromdjango.contribimportadminfromdjango.urlsimportinclude,pathurlpatterns=[path("polls/",include("polls.urls")),path("admin/",admin.site.urls),]

Thepath() function expects at least two arguments:route andview.Theinclude() function allows referencing other URLconfs.Whenever Django encountersinclude(), it chops off whateverpart of the URL matched up to that point and sends the remaining string to theincluded URLconf for further processing.

The idea behindinclude() is to make it easy toplug-and-play URLs. Since polls are in their own URLconf(polls/urls.py), they can be placed under “/polls/”, or under“/fun_polls/”, or under “/content/polls/”, or any other path root, and theapp will still work.

When to useinclude()

You should always useinclude() when you include other URL patterns.The only exception isadmin.site.urls, which is a pre-built URLconfprovided by Django for the default admin site.

You have now wired anindex view into the URLconf. Verify it’s working withthe following command:

$pythonmanage.pyrunserver
...\> py manage.py runserver

Go tohttp://localhost:8000/polls/ in your browser, and you should see thetext “Hello, world. You’re at the polls index.”, which you defined in theindex view.

Page not found?

If you get an error page here, check that you’re going tohttp://localhost:8000/polls/ and nothttp://localhost:8000/.

When you’re comfortable with the basic request and response flow, readpart 2 of this tutorial to start working with thedatabase.

Back to Top

Additional Information

Support Django!

Support Django!

Contents

Getting help

FAQ
Try the FAQ — it's got answers to many common questions.
Index,Module Index, orTable of Contents
Handy when looking for specific information.
Django Discord Server
Join the Django Discord Community.
Official Django Forum
Join the community on the Django Forum.
Ticket tracker
Report bugs with Django or Django documentation in our ticket tracker.

Download:

Offline (Django 5.2):HTML |PDF |ePub
Provided byRead the Docs.


[8]ページ先頭

©2009-2025 Movatter.jp