--- title: Введення в Django slug: Learn/Server-side/Django/Introduction tags: - CodingScripting - Intro - Learn - Python - Server-side programming - django - Джанго - Кодування - Програмування - Пітон - уроки translation_of: Learn/Server-side/Django/Introduction ---
У цій першій статті Django, ми відповімо на питання "Що таке Django?" і даємо вам обзор того, що робить цей веб-фреймворк особливим. Ми розглянемо основні характеристики, включаючи деякі додаткові функціональні можливості модуля, які ми не встигли ще обговорити. Ми також покажемо вам деякі з основних блоків програми Django (хоча на даний момент у вас ще немає середовища розробки, в якій можна було б її протестувати).
Передумови:: | Basic computer literacy. A general understanding of server-side website programming, and in particular the mechanics of client-server interactions in websites. |
---|---|
Завдання: | To gain familiarity with what Django is, what functionality it provides, and the main building blocks of a Django application. |
Django - це високорівневий веб-фреймворк Python, що дозволяє швидко розвивати безпечні та підтримувані сайти. Побудований досвідченими розробниками, Django піклується про більшу частину турбот про веб-розробку, тому ви можете зосередитися на написанні програми без необхідності винаходити колесо.Це вільний і відкритий код, має процвітаюче і активне співтовариство, велику документацію, і безліч варіантів для безкоштовної і платної підтримки.
Django допоможе вам написати програмне забезпечення, яке:
Django was initially developed between 2003 and 2005 by a web team who were responsible for creating and maintaining newspaper websites. After creating a number of sites, the team began to factor out and reuse lots of common code and design patterns. This common code evolved into a generic web development framework, which was open-sourced as the "Django" project in July 2005.
Django has continued to grow and improve, from its first milestone release (1.0) in September 2008 through to the recently-released version 2.0 (2017). Each release has added new functionality and bug fixes, ranging from support for new types of databases, template engines, and caching, through to the addition of "generic" view functions and classes (which reduce the amount of code that developers have to write for a number of programming tasks).
Note: Check out the release notes on the Django website to see what has changed in recent versions, and how much work is going into making Django better.
Django is now a thriving, collaborative open source project, with many thousands of users and contributors. While it does still have some features that reflect its origin, Django has evolved into a versatile framework that is capable of developing any type of website.
There isn't any readily-available and definitive measurement of popularity of server-side frameworks (although sites like Hot Frameworks attempt to assess popularity using mechanisms like counting the number of GitHub projects and StackOverflow questions for each platform). A better question is whether Django is "popular enough" to avoid the problems of unpopular platforms. Is it continuing to evolve? Can you get help if you need it? Is there an opportunity for you to get paid work if you learn Django?
Based on the number of high profile sites that use Django, the number of people contributing to the codebase, and the number of people providing both free and paid for support, then yes, Django is a popular framework!
High-profile sites that use Django include: Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic, Open Knowledge Foundation, Pinterest, and Open Stack (source: Django home page).
Web frameworks often refer to themselves as "opinionated" or "unopinionated".
Opinionated frameworks are those with opinions about the "right way" to handle any particular task. They often support rapid development in a particular domain (solving problems of a particular type) because the right way to do anything is usually well-understood and well-documented. However they can be less flexible at solving problems outside their main domain, and tend to offer fewer choices for what components and approaches they can use.
Unopinionated frameworks, by contrast, have far fewer restrictions on the best way to glue components together to achieve a goal, or even what components should be used. They make it easier for developers to use the most suitable tools to complete a particular task, albeit at the cost that you need to find those components yourself.
Django is "somewhat opinionated", and hence delivers the "best of both worlds". It provides a set of components to handle most web development tasks and one (or two) preferred ways to use them. However, Django's decoupled architecture means that you can usually pick and choose from a number of different options, or add support for completely new ones if desired.
In a traditional data-driven website, a web application waits for HTTP requests from the web browser (or other client). When a request is received the application works out what is needed based on the URL and possibly information in POST
data or GET
data. Depending on what is required it may then read or write information from a database or perform other tasks required to satisfy the request. The application will then return a response to the web browser, often dynamically creating an HTML page for the browser to display by inserting the retrieved data into placeholders in an HTML template.
Django web applications typically group the code that handles each of these steps into separate files:
Note: Django refers to this organisation as the "Model View Template (MVT)" architecture. It has many similarities to the more familiar Model View Controller architecture.
The sections below will give you an idea of what these main parts of a Django app look like (we'll go into more detail later on in the course, once we've set up a development environment).
A URL mapper is typically stored in a file named urls.py. In the example below, the mapper (urlpatterns
) defines a list of mappings between routes (specific URL patterns) and corresponding view functions. If an HTTP Request is received that has a URL matching a specified pattern then the associated view function will be called and passed the request.
urlpatterns = [ path('admin/', admin.site.urls), path('book/<int:id>/', views.book_detail, name='book_detail'), path('catalog/', include('catalog.urls')), re_path(r'^([0-9]+)/$', views.best), ]
The urlpatterns
object is a list of path()
and/or re_path()
functions (Python lists are defined using square brackets, where items are separated by commas and may have an optional trailing comma. For example: [item1, item2, item3,]
).
The first argument to both methods is a route (pattern) that will be matched. The path()
method uses angle brackets to define parts of a URL that will be captured and passed through to the view function as named arguments. The re_path()
function uses a flexible pattern matching approach known as a regular expression. We'll talk about these in a later article!
The second argument is another function that will be called when the pattern is matched. The notation views.book_detail
indicates that the function is called book_detail()
and can be found in a module called views
(i.e. inside a file named views.py
)
Views are the heart of the web application, receiving HTTP requests from web clients and returning HTTP responses. In between, they marshall the other resources of the framework to access databases, render templates, etc.
The example below shows a minimal view function index()
, which could have been called by our URL mapper in the previous section. Like all view functions it receives an HttpRequest
object as a parameter (request
) and returns an HttpResponse
object. In this case we don't do anything with the request, and our response simply returns a hard-coded string. We'll show you a request that does something more interesting in a later section.
# filename: views.py (Django view functions) from django.http import HttpResponse def index(request): # Get an HttpRequest - the request parameter # perform operations using information from the request. # Return HttpResponse return HttpResponse('Hello from Django!')
Note: A little bit of Python:
HttpResponse
object from the django.http
module so that we can use it in our view: from django.http import HttpResponse
. There are other ways of importing some or all objects from a module.def
keyword as shown above, with named parameters listed in brackets after the name of the function; the whole line ends in a colon. Note how the next lines are all indented. The indentation is important, as it specifies that the lines of code are inside that particular block (mandatory indentation is a key feature of Python, and is one reason that Python code is so easy to read).Views are usually stored in a file called views.py.
Django web applications manage and query data through Python objects referred to as models. Models define the structure of stored data, including the field types and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc. The definition of the model is independent of the underlying database — you can choose one of several as part of your project settings. Once you've chosen what database you want to use, you don't need to talk to it directly at all — you just write your model structure and other code, and Django handles all the dirty work of communicating with the database for you.
The code snippet below shows a very simple Django model for a Team
object. The Team
class is derived from the django class models.Model
. It defines the team name and team level as character fields and specifies a maximum number of characters to be stored for each record. The team_level
can be one of several values, so we define it as a choice field and provide a mapping between choices to be displayed and data to be stored, along with a default value.
# filename: models.py from django.db import models class Team(models.Model): team_name = models.CharField(max_length=40) TEAM_LEVELS = ( ('U09', 'Under 09s'), ('U10', 'Under 10s'), ('U11', 'Under 11s'), ... #list other team levels ) team_level = models.CharField(max_length=3, choices=TEAM_LEVELS, default='U11')
Note: A little bit of Python:
class
to define the "blueprint" for an object. We can create multiple specific instances of the type of object based on the model in the class.Team
class, which derives from the Model
class. This means it is a model, and will contain all the methods of a model, but we can also give it specialized features of its own too. In our model we define the fields our database will need to store our data, giving them specific names. Django uses these definitions, including the field names, to create the underlying database.The Django model provides a simple query API for searching the database. This can match against a number of fields at a time using different criteria (e.g. exact, case-insensitive, greater than, etc.), and can support complex statements (for example, you can specify a search on U11 teams that have a team name that starts with "Fr" or ends with "al").
The code snippet shows a view function (resource handler) for displaying all of our U09 teams. The line in bold shows how we can use the model query API to filter for all records where the team_level
field has exactly the text 'U09' (note how this criteria is passed to the filter()
function as an argument with the field name and match type separated by a double underscore: team_level__exact).
## filename: views.py from django.shortcuts import render from .models import Team def index(request): list_teams = Team.objects.filter(team_level__exact="U09") context = {'youngest_teams': list_teams} return render(request, '/best/index.html', context)
This function uses the render()
function to create the HttpResponse
that is sent back to the browser. This function is a shortcut; it creates an HTML file by combining a specified HTML template and some data to insert in the template (provided in the variable named "context
"). In the next section we show how the template has the data inserted in it to create the HTML.
Template systems allow you to specify the structure of an output document, using placeholders for data that will be filled in when a page is generated. Templates are often used to create HTML, but can also create other types of document. Django supports both its native templating system and another popular Python library called Jinja2 out of the box (it can also be made to support other systems if needed).
The code snippet shows what the HTML template called by the render()
function in the previous section might look like. This template has been written under the assumption that it will have access to a list variable called youngest_teams
when it is rendered (contained in the context
variable inside the render()
function above). Inside the HTML skeleton we have an expression that first checks if the youngest_teams
variable exists, and then iterates it in a for
loop. On each iteration the template displays each team's team_name
value in an {{htmlelement("li")}} element.
## filename: best/templates/best/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Home page</title> </head> <body> {% if youngest_teams %} <ul> {% for team in youngest_teams %} <li>\{\{ team.team_name \}\}</li> {% endfor %} </ul> {% else %} <p>No teams are available.</p> {% endif %} </body> </html>
The preceding sections show the main features that you'll use in almost every web application: URL mapping, views, models and templates. Just a few of the other things provided by Django include:
Congratulations, you've completed the first step in your Django journey! You should now understand Django's main benefits, a little about its history, and roughly what each of the main parts of a Django app might look like. You should have also learned a few things about the Python programming language, including the syntax for lists, functions, and classes.
You've already seen some real Django code above, but unlike with client-side code, you need to set up a development environment to run it. That's our next step.