Website Development
Trending

Best Python Framework: Django How Popular Is Django?

Dango is a very popular and powerful Python-based open-source web framework. In this article, you’ll get a clear view that is Django the best Python framework and how popular is Django?

Intro to Django

In this first Django article, we’ll answer the following question, “What is Django?”, and show you what’s special about this application framework (also called framework).

We will then see the main features, but also some advanced features that unfortunately we will not have time to see in detail in this module. We’ll also show you how a Django application works (although we don’t have an environment to test it in).

Prerequisites:Basic programming knowledge. A general understanding of server-side programming as well as an understanding of client-server interactions in websites.
Goal:Become familiar with Django by understanding what it is, the functionality it provides, and the main building blocks of a Django application.

What is Django?

Django is a high-level Python framework, that allows rapid development of secure, maintainable websites. Created by experienced developers, Django takes most of the hassle out of web development, so you can focus on writing your app without reinventing the wheel.

It’s free, open-source, has an active community, good documentation, and several options for free and non-free support.

Django helps you write an application that is:

Complete

Django follows the “Batteries Included” philosophy and provides almost anything developers might want. As everything you need is a part of this “product”, everything works perfectly together, following consistent design principles, it also has complete and up-to-date documentation.

Versatile

Django can be (and has been) used to create almost any kind of site — from data managers to wikis, to social networks and news sites. It can work with any client-side framework and can return data in almost any format (including HTML, RSS, JSON, XML, etc.). The site you’re reading about right now is based on Django!

Secure

Django helps developers avoid common security mistakes by providing an infrastructure designed to “do the right thing” to protect websites automatically.

For example, Django provides a secure way to manage user accounts and passwords, avoiding common mistakes like putting session information in cookies, where they are vulnerable (instead cookies only contain a key, and the data is stored in the database), or directly store passwords, instead of hashed passwords.

A hashed password is a fixed-length value created bypassing the password through a cryptographic hash function. Django can check if an entered password is correct by passing it through the hash function and comparing the return with the value stored in the database.

Django enables protection against many vulnerabilities by default, such as SQL injection, cross-site scripting, cross-site request forgery, and clickjacking (see Website security for more details on such attacks).

Scalable

Django uses a “shared-nothing” composite architecture (each component of the architecture is independent of the others, and can thus be replaced or changed as needed).

By having clear separations between the different parts, Django can scale during an increase in traffic by adding hardware at all levels: cache servers, database servers, and application servers. Some of the most popular sites have managed to scale Django to meet their demand (eg Instagram and Disqus to name a few).

Maintainable

Django code design principles encourage the creation of code that is easy to maintain and reusable. In particular, it uses the Don’t Repeat Yourself (DRY) philosophy to avoid any superfluous duplication, reducing the size of your code. f the Model-View-Controller (MVC) architecture pattern). ).

Portable

Django is written in Python, which runs on various platforms. This means that you will no longer be constrained by a particular platform, and you will be able to run your applications under as many versions of Windows, Linux, and Mac OS X as you wish.

Where Is It From?

Django was developed and launched in 2003 and 2005 by a web team responsible for creating and maintaining journalistic sites. After creating several sites, the team began to exclude and reuse recurring code and architecture patterns.

This recurring code eventually evolved into a generic web development framework, which was made available as open-source under the “Django” project in July 2005.

Django has continued to develop and improve, from its first release (1.0) in September 2008 to the recently released 2.0 (2017).

Each release has added new features and bug fixes, ranging from support for new database types, template engines, and caching, to the addition of ‘generic’ view classes and functions (which reduce the number of code developers has to write for a whole host of programming tasks).

Note: Check the release notes on the Django website to see changes made in recent releases, as well as all the work done to improve Django.

Now, Django is a thriving collaborative open-source project, with several thousand users and contributors. Although many features still reflect its origins, Django has evolved into a versatile framework capable of developing any type of website.

How popular is Django?

There is no ready-made, definitive measure of the popularity of server-facing frameworks yet (although sites like Hot Frameworks attempt to estimate this popularity using means like counting GitHub projects and questions on StackOverflow to each platform).

A better question would instead be is Django “popular enough” to avoid the problems of less popular platforms. Will it continue to evolve? Can you get help if you need it? Will you have job opportunities if you learn Django?

Based on the number of popular websites that use Django, the number of people contributing its source code, and the number of people providing free or paid support, then yes, Django is a popular framework! Django is a very popular framework that’s why it’s also compared with several other frameworks like SpringBoot, Express, Node.js, etc.

Websites that use Django include Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic, Open Knowledge Foundation, Pinterest, and Open Stack.

Is Django restrictive?

Web frameworks like PHP are often referred to as “restrictive” or “non-restrictive”.

Restrictive frameworks are those that give you the “right way” to do a particular task but then they often underlie rapid development in a particular area (solving problems of a particular type), as this right way of doing things is often well understood and well documented. However, they may be less flexible in their abilities to solve problems outside of their domain, and often offer less choice of usable components and approaches.

In contrast, non-restrictive frameworks have fewer restrictions on how best to fit components together to achieve a goal, or even on which components to use. They simplify the developer’s task by allowing them to use the tools best suited to performing a particular task, at the cost, however, of the developer’s need to find these components. This will help us know that how popular is Django?

Django is “more or less restrictive”, and thus offers the “best of each approach”. It provides a set of components to handle most web development tasks along with one (or two) preferred approaches to using them. However, Django’s decoupled architecture means that you can usually choose from several different options, or provide support for completely new approaches if you so desire.

What does Django code look like?

In a traditional data-oriented website, a web application waits for an HTTP request from a web browser (or any other client). When a request is received, the application understands its needs based on the URL and sometimes based on POSTdata or GETdata information.

Depending on what is expected, it can then read or write the information to a database or perform some other task required to satisfy the request.

Django web apps typically bundle the code that handles each of these steps into separate files:

Working Of Django How Popular is django
  • URLs: While it’s possible to handle requests for each URL through a single function, it’s far more viable to write an isolated view function that will handle each resource. The URL mapper can also match patterns of strings or numbers that appear in a URL and pass these as data in a view function.
  • Views: A view is a request handling function, which receives HTTP requests and returns HTTP responses. Views access the data needed to satisfy requests via templates and delegate the formatting of responses to templates.
  • Models: Models are Python objects, which define the data structure of an application, and provide mechanisms for managing (adding, modifying, deleting) and querying records from a database.

The sections below will give you an idea of ​​what these different parts of a Django application look like (we’ll get to more details later in the game, once we’ve set up the development environment).

Send the request to the correct view (urls.py)

The URL mapper is usually stored in a file named urls.py. In the example below, the mapper( URL patterns) defines a list of mappings between routes ( specific URL patterns *)* and their corresponding view function.

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 object urlpatternsis a list of functions path()and/or re_path()(lists in Python 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 of each method is a route (pattern) that will be recognized. The function re_path()uses a flexible pattern matching approach, known as a regular expression.

The second argument is another function that will be called when the pattern is recognized. The notation views. book-detail indicates that the function is called book-detail() and that it is in a called module views(ie in a file called views.py)

Process the request (views.py)

Views are the heart of web applications. They receive HTTP requests from web clients and return HTTP responses. In the meantime, they mobilize the other resources of the framework to access the databases, prepare the rendering of the templates, etc.

The example below shows a minimal view function index(), which could be called by our URL mapper from the previous section. Like all view functions, it receives an object HttpRequestas a parameter ( request) and returns an object HttpResponse. In our case, we don’t do anything special with the query, and our response only returns a raw string. We will show a more interesting query in another section.

from django.http import HttpResponse

def index(request):

    return HttpResponse(‘Hello from Django!’)

Note: A bit of Python:

  • Python modules are libraries of functions, stored in separate files that we may want to use in our code. Here we import the HttpResponsemodule object Django.HTTPS that we can use in our view: from Django. http import HttpResponse. There are other ways to import some objects (or all objects) of a module.
  • Functions are declared using the keyword and default shown above, with named parameters listed in parentheses after the function name; the line then ends with a colon.

Views are usually stored in a file named views.py.

Define data models (models.py)

Django web applications manage and query data through Python objects called models. Templates define the structure of stored data, which includes field types and their maximum size if needed, default values, selectable list options, and help text for documentation — you can choose what you need based on your project specifications.

Once you’ve chosen the database you want to use, you don’t need to communicate with it directly at all — you just have to write the structure of your model, Django takes care of the dirty work of communication with the database for you.

The class Team is derived from the Django class models. Model.

# nom du fichier : 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’),

        …  # lister les autres niveaux d’équipes

    )

    team_level = models.CharField(max_length=3,choices=TEAM_LEVELS,default=’U11′)

Note: A bit of Python:

  • Python supports “object-oriented programming”, a type of programming where we organize our code into objects, which includes data and related functions that will act on the data. In Python, we use the keyword class to define the “skeleton” of an object.
  • So for example, here we have a class Team, derived from the class model. In our model, we define the fields that our database will need, giving them specific names. Django will use these definitions, which also include field names, to create the underlying database.

Query data (views.py)

The Django model provides a simplified query API that allows us to query a database. This API can include multiple fields at once supporting multiple criteria (eg exactly, case insensitive, greater than, etc.), and can support complex declarations (for example, you can specify a search on U11 teams with a team name starting with “Fr” or ending with “al”).

The code snippet below shows a view function (resource manager) displaying all of our U09 teams. The bold line shows how one can use the Query API to filter out all records where the field team_levelstrictly consists of the text ‘U09’ (note how this criterion is passed into the function filter()as an argument, where the field name and type matches are separated by a double underscore: team_level__exact ).

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)

copy to This function uses the function render()to create the HttpResponsewhich is returned to the browser. This function is a shortcut; it creates an HTML file by combining a specific HTML template and data to be inserted into the template (provided in the variable called ” context”). In the next section, we show you how data is inserted into the template to generate the HTML.

Return data (HTML templates)

Template systems allow you to specify the structure of an output document, using placeholders that will be substituted with data when the page is generated. Templates are often used to create HTML, but they can also be used to create other types of documents. Django supports both its native templating system as well as another popular out-of-the-box Python library called Jinja2 (it can also support other systems as needed).

The code snippet below shows what the HTML template from the previous section might look like when called by the function render(). This template was written with the assumption that it would have access to a list of variables called youngest_teamswhen called. generated (contained in the variable context in the render()above function). In the HTML skeleton, we have an expression that first checks that the variable youngest_teamsexists, then iterates over it in a loop. At each iteration, the template displays the value team_nameof each team in an element <li>.

<!DOCTYPE html>

<html lang=”en”>

<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>

What else can you do?

The previous sections present the main features that you will use in almost all your web applications: URL mapping, views, models, and templates. Other features offered by Django include:

  • Forms: HTML forms are used to collect user data which will be processed on the server. Django simplifies form creation, validation, and processing.
  • User authentication and permissions: Django includes a robust user authentication and permissions management system built with security as a priority in its design.
  • Cache: Generating content dynamically requires far more computational resources (and is slower) than serving static content. Django provides a flexible caching system that allows you to store all or part of a page so that it is regenerated only when needed.
  • Site administration: Site administration with Django is included by default when you create an application using the basic skeleton. Django makes it very easy to create an admin page where admins can create, edit, and view any data model on your site.
  • Data serialization: Django makes it easy to serialize and serve your data in XML or JSON. This can be useful if you are creating a web service (a website whose sole purpose is to serve data that will be used by other applications or sites but does not display anything by itself), or when you create a website where the client-side code takes care of displaying the data.

Summary

Congratulations, you have reached the first step in your journey with Django! By now you should understand the main benefits of Django, know a bit more about its history, and roughly what each part of your Django application looks like. You should also have learned 2-3 things about the Python programming language, which includes the syntax of lists, functions, and classes. We think that this

the question that how popular is Django?

You’ve already seen some real Django code above, but unlike client-side code, you’ll need to set up a development environment to use it. This is our next step.

Also, Check

Leave a Reply

Your email address will not be published.

Back to top button

AdBlock Detected

Please Disable the AdBlock! :)