Home  >  Article  >  Backend Development  >  Using Django in Python: from beginner to advanced programming

Using Django in Python: from beginner to advanced programming

WBOY
WBOYOriginal
2023-06-22 14:51:072175browse

With the popularity of the Python language, the Django framework has become a popular web development framework. The Django framework's rich functions and ability to improve development efficiency make developers flock to it. This article will introduce some introductory knowledge of the Django framework and provide some advanced programming skills to help beginners better understand and master the use of Django.

The Django framework is an open source web framework built on the Python language. Its design philosophy is "based on reality, simple and practical", mainly based on the MVC (Model-View-Controller) design pattern, and provides complete web development functions, including database interface, URL routing, form processing, and template rendering. and user authentication, etc.

Django installation

Before we start using Django, we need to install Django first. You can use pip to install Django: just run the command pip install Django.

The basic structure of Django

Django is divided into multiple components, including model, view and template. Their definitions are as follows:

  1. Model: used to define the interaction between data structures and databases.
  2. View (View): Process user requests, construct HttpResponse objects, and complete the response by rendering templates.
  3. Template: used to define the display form of web pages.

Django’s URL configuration

URL configuration is the basis for monitoring all HTTP requests and dispatching them to the appropriate views. In Django, you can configure the URL in the project's urls.py file, for example:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('about/', views.about, name='about'),
]

The above is a simple URL configuration example. It defines two URLs: one is the homepage of the root directory, and the other is the about page of /about/. The path sends the request to the index() and about() view functions in the views.py file. The view functions are defined in the next section.

Django’s view function

In Django, the view function is the code that responds to user requests. They construct HttpResponse objects based on the path in the URL configuration. The form of the view function is as follows:

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, World!")

The above is a simple index() view function example. It responds to HTTP requests and returns a "Hello, World!" string.

Django’s template

Django’s template is the code used to define the style of a web page. They allow you to embed Python code into HTML to construct dynamic web pages. Template files are stored in the project/app/templates/ directory. Here is an example of a template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
</head>
<body>
    <p>{{ content }}</p>
</body>
</html>

In templates, {{ }} is used to specify blocks of Python code where variables can be accessed and conditions and loops executed. In the above example, title and content variables are passed to the template in the view function to dynamically generate titles and paragraphs.

Django’s model

Django’s model is the code used to define the interaction between data structures and databases. They allow you to easily work with database records in a Pythonic way. Model definitions are stored in the app/models.py file. The following is an example of a model:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200)
    pub_date = models.DateField()

    def __str__(self):
        return self.title

In the above example, we have defined a Book model, which has title, author and pub_date attributes. The function __str__() defines the string representation of the model. This model uses Django's default SQLite database for storage, you can use other databases such as mysql as an alternative.

Advanced Programming Tips for Django

  1. Static File Processing

Django supports processing static files such as CSS, JavaScript, and images. Add the following line in the settings.py file:

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    '/var/www/static/',
]

STATIC_ROOT = '/var/www/static_files/'

In /templates/my_template.html you can include this line of code:

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'my_style.css' %}">

The above line of code allows access from the static folder Load the my_style.css style file.

  1. User Authentication

Django provides a user authentication system that allows you to easily implement role-based access control and ensure that users receive the correct information when accessing protected pages. authentication. To use this feature, you first need to import the following from the Django.contrib.auth module:

from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout

Then you can mark the protected view with the @loginrequired decorator and log in using the authenticate, login, and logout functions and logout process.

  1. Testing

Django has a testing framework that allows you to write test cases and ensure that your application works properly under any circumstances. To write test cases, create a tests.py file and import Django’s TestCase class. The following is an example of a test case:

from django.test import TestCase
from django.urls import reverse

class MyAppTests(TestCase):
    def test_index(self):
        response = self.client.get(reverse('index'))
        self.assertEqual(response.status_code, 200)

In the above example, we created a TestClass named MyAppTests and added a test case test_index. We use Django's client object to simulate the request and ensure that an HTTP 200 response code is returned.

Summary

Django framework is a powerful web development framework that provides a complete and easy-to-use toolset for rapid development of web applications. Using the basic concepts and advanced programming techniques provided in this article, you can easily build Django web applications and gain a deep understanding of using Django.

The above is the detailed content of Using Django in Python: from beginner to advanced programming. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn