Writing your first Django app, part 1 | Django documentation (2024)

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 have Django installed already. You cantell Django is installed and which version by running the following commandin a shell prompt (indicated by the $ prefix):

$ python -m django --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.1, 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, check What Python version can I use with Django? to find a compatibleversion of Django.

See How to install Django for advice on how to removeolder versions of Django and install a newer one.

Where to get help:

If you’re having trouble going through this tutorial, please head over tothe Getting 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 aDjango project – 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, then run the following command:

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

This will create a mysite directory in your current directory. If it didn’twork, see Problems 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) or test (whichconflicts with a built-in Python package).

Let’s look at what startproject created:

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

These files are:

  • The outer mysite/ root directory is a container for your project. Itsname doesn’t matter to Django; you can rename it to anything you like.
  • manage.py: A command-line utility that lets you interact with thisDjango project in various ways. You can read all the details aboutmanage.py in django-admin and manage.py.
  • The inner mysite/ directory 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,read more 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 in URL dispatcher.
  • mysite/asgi.py: An entry-point for ASGI-compatible web servers toserve your project. See How to deploy with ASGI for more details.
  • mysite/wsgi.py: An entry-point for WSGI-compatible web servers toserve your project. See How to deploy with WSGI for more details.

The development server

Let’s verify your Django project works. Change into the outer mysite directory, ifyou haven’t already, and run the following commands:

$ python manage.py runserver
...\> 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.August 13, 2024 - 15:50:53Django version 5.1, using settings 'mysite.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.

Note

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

Now that the server’s running, visit http://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 the runserver reference.)

Automatic reloading of runserver

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 on your Python path. Inthis tutorial, we’ll create our poll app in the same directory as yourmanage.py file so that it can be imported as its own top-level module,rather than a submodule of mysite.

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

$ python manage.py startapp polls
...\> py manage.py startapp polls

That’ll create a directory polls, 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 file polls/views.pyand put the following Python code in it:

polls/views.py

from django.http import HttpResponsedef index(request): return HttpResponse("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 named urls.py.

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

polls/urls.py

from django.urls import pathfrom . import viewsurlpatterns = [ 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 global URLconf in the mysite project toinclude the URLconf defined in polls.urls. To do this, add an import fordjango.urls.include in mysite/urls.py and insert aninclude() in the urlpatterns list, so you have:

mysite/urls.py

from django.contrib import adminfrom django.urls import include, pathurlpatterns = [ path("polls/", include("polls.urls")), path("admin/", admin.site.urls),]

The include() function allows referencing other URLconfs.Whenever Django encounters include(), 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 behind include() 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 use include()

You should always use include() when you include other URL patterns.admin.site.urls is the only exception to this.

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

$ python manage.py runserver
...\> py manage.py runserver

Go to http://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 not http://localhost:8000/.

The path() function is passed four arguments, two required:route and view, and two optional: kwargs, and name.At this point, it’s worth reviewing what these arguments are for.

path() argument: route

route is a string that contains a URL pattern. When processing a request,Django starts at the first pattern in urlpatterns and makes its way downthe list, comparing the requested URL against each pattern until it finds onethat matches.

Patterns don’t search GET and POST parameters, or the domain name. For example,in a request to https://www.example.com/myapp/, the URLconf will look formyapp/. In a request to https://www.example.com/myapp/?page=3, theURLconf will also look for myapp/.

path() argument: view

When Django finds a matching pattern, it calls the specified view function withan HttpRequest object as the first argument and any“captured” values from the route as keyword arguments. We’ll give an exampleof this in a bit.

path() argument: kwargs

Arbitrary keyword arguments can be passed in a dictionary to the target view. Wearen’t going to use this feature of Django in the tutorial.

path() argument: name

Naming your URL lets you refer to it unambiguously from elsewhere in Django,especially from within templates. This powerful feature allows you to makeglobal changes to the URL patterns of your project while only touching a singlefile.

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

Writing your first Django app, part 1 | Django documentation (2024)

FAQs

Can I learn Django from documentation? ›

Depending how new you are to Django, you can try a tutorial, or just dive into the documentation. Want to learn more about Django? Read the overview to see whether Django is right for your project.

How to create documentation for Django project? ›

The Django admin documentation generator¶
  1. Add django. contrib. admindocs to your INSTALLED_APPS .
  2. Add path('admin/doc/', include('django. contrib. admindocs. urls')) to your urlpatterns . ...
  3. Install the docutils 0.19+ package.
  4. Optional: Using the admindocs bookmarklets requires django. contrib. admindocs. middleware.

Which command is used to create the first project in Django? ›

Command Reference
StepDescriptionCommand
2aInstall Djangopython -m pip install django
2bPin your dependenciespython -m pip freeze > requirements.txt
3Set up a Django projectdjango-admin startproject <projectname>
4Start a Django apppython manage.py startapp <appname>
2 more rows

How to add an app in Django project? ›

Add a new app to the Django project
  1. Do one of the following: Go to Tools | Run manage.py task or press Ctrl Alt 0R . ...
  2. Specify the name of the app and press Enter .
  3. The app directory with the required files is added to the project structure. The app is also added to INSTALLED_APPS in settings.py.
Jun 17, 2024

Can I learn Django in 3 days? ›

As with any skill, learning how to master Django takes time and practice. If you already know Python and are familiar with technical concepts like terminology authentication, URL routing and API, you may be able to learn all you need to use Django in as little as two to three weeks.

Can I learn Django in 20 days? ›

Django is a high-level Python web framework used to build websites and web applications rapidly and securely. Web Developers, Python Developers, and Data Scientists use Django. It takes the average learner between one to four weeks to learn Django.

What format is Django documentation? ›

Django's documentation uses the Sphinx documentation system, which in turn is based on docutils. The basic idea is that lightly-formatted plain-text documentation is transformed into HTML, PDF, and any other output format.

What is the difference between app and project in Django? ›

An app is a web application that does something – e.g., a blog system, a database of public records or a small poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.

Is Django front-end or backend? ›

Django is a web development framework that developers primarily use for backend web development. It is written in Python and provides a set of tools and libraries to help you build web apps quickly and efficiently. Although Django offers some support for front-end development, its main focus is on the backend.

Is Django better than Flask? ›

Flask: Ideal for smaller projects or prototypes due to its lightweight nature and minimalistic design. Offers flexibility and simplicity, making it suitable for rapid development. Django: Suited for larger, more complex projects requiring robust features and scalability.

Which is better, Django or React? ›

So which is better for Web Development? Django excels in Backend Development, while React shines in Frontend Development. Many developers prefer using Django for Backend and React for Frontend.

How to create a simple app in Django? ›

Write your first view¶
  1. Let's write the first view. ...
  2. This is the most basic view possible in Django. ...
  3. To define a URLconf for the polls app, create a file polls/urls.py with the following content:
  4. The next step is to configure the global URLconf in the mysite project to include the URLconf defined in polls.urls .

Can I make a mobile app with Django? ›

You can convert your Django website to an Android app in minutes with our software. Users can visit your website directly from the mobile app. All you need is you website URL and your FREE Django to APK file will be generated for your Android application.

What is the best way to learn Django? ›

Here are some extra tips to accelerate your Django learning process.
  1. Start with a solid Python foundation. A firm grasp of Python fundamentals will help you understand Django more easily. ...
  2. Work on projects. ...
  3. Learn from the documentation. ...
  4. Join a Django community. ...
  5. Practice regularly. ...
  6. Stay in the loop. ...
  7. Seek mentorship.
Jan 3, 2024

How good is Django documentation? ›

Django's main documentation is broken up into “chunks” designed to fill different needs: The introductory material is designed for people new to Django – or to web development in general. It doesn't cover anything in depth, but instead gives a high-level overview of how developing in Django “feels”.

Is Django difficult to learn? ›

Django, a high-level Python web framework, enables the rapid development of secure websites you can actually maintain. While it's more difficult to learn than Flask, if you have strong foundational knowledge in Python and web development, you'll have an easier time picking it up.

Is Django harder to learn than Flask? ›

Flask can be difficult to hire for too, but it tends to be easier than Django since it's a light weight framework with fewer abstraction layers. A strong developer with experience in a similar framework in a different language, like Express.

References

Top Articles
Gracie Abrams tickets, here's when tickets for UK arena tour come out
Holiday packing list with useful holiday tips
Spasa Parish
Rentals for rent in Maastricht
159R Bus Schedule Pdf
Sallisaw Bin Store
Black Adam Showtimes Near Maya Cinemas Delano
Espn Transfer Portal Basketball
Pollen Levels Richmond
11 Best Sites Like The Chive For Funny Pictures and Memes
Things to do in Wichita Falls on weekends 12-15 September
Craigslist Pets Huntsville Alabama
Paulette Goddard | American Actress, Modern Times, Charlie Chaplin
What's the Difference Between Halal and Haram Meat & Food?
R/Skinwalker
Rugged Gentleman Barber Shop Martinsburg Wv
Jennifer Lenzini Leaving Ktiv
Justified - Streams, Episodenguide und News zur Serie
Epay. Medstarhealth.org
Olde Kegg Bar & Grill Portage Menu
Cubilabras
Half Inning In Which The Home Team Bats Crossword
Amazing Lash Bay Colony
Juego Friv Poki
Dirt Devil Ud70181 Parts Diagram
Truist Bank Open Saturday
Water Leaks in Your Car When It Rains? Common Causes & Fixes
What’s Closing at Disney World? A Complete Guide
New from Simply So Good - Cherry Apricot Slab Pie
Drys Pharmacy
Ohio State Football Wiki
Find Words Containing Specific Letters | WordFinder®
FirstLight Power to Acquire Leading Canadian Renewable Operator and Developer Hydromega Services Inc. - FirstLight
Webmail.unt.edu
2024-25 ITH Season Preview: USC Trojans
Metro By T Mobile Sign In
Restored Republic December 1 2022
Lincoln Financial Field Section 110
Free Stuff Craigslist Roanoke Va
Stellaris Resolution
Wi Dept Of Regulation & Licensing
Pick N Pull Near Me [Locator Map + Guide + FAQ]
Crystal Westbrooks Nipple
Ice Hockey Dboard
Über 60 Prozent Rabatt auf E-Bikes: Aldi reduziert sämtliche Pedelecs stark im Preis - nur noch für kurze Zeit
Wie blocke ich einen Bot aus Boardman/USA - sellerforum.de
Infinity Pool Showtimes Near Maya Cinemas Bakersfield
Dermpathdiagnostics Com Pay Invoice
How To Use Price Chopper Points At Quiktrip
Maria Butina Bikini
Busted Newspaper Zapata Tx
Latest Posts
Article information

Author: Saturnina Altenwerth DVM

Last Updated:

Views: 6127

Rating: 4.3 / 5 (44 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Saturnina Altenwerth DVM

Birthday: 1992-08-21

Address: Apt. 237 662 Haag Mills, East Verenaport, MO 57071-5493

Phone: +331850833384

Job: District Real-Estate Architect

Hobby: Skateboarding, Taxidermy, Air sports, Painting, Knife making, Letterboxing, Inline skating

Introduction: My name is Saturnina Altenwerth DVM, I am a witty, perfect, combative, beautiful, determined, fancy, determined person who loves writing and wants to share my knowledge and understanding with you.