Home  >  Article  >  Backend Development  >  Django Programming Guide: The Road to Mastery in Python Web Programming

Django Programming Guide: The Road to Mastery in Python Web Programming

PHPz
PHPzOriginal
2023-06-23 13:32:20948browse

Django is a web framework based on the Python language. It is a powerful and easy-to-use tool for building efficient and secure web applications. Django is based on the MVC (Model-View-Controller) pattern and makes web development more efficient and controllable by providing predefined components and design patterns. The framework is widely used across the globe, including some famous websites and web applications. If you're learning Django programming, this article will provide some useful guides and tips to help you better understand and master this powerful tool.

1. Install and set up Django

Before you start using Django, you need to ensure that you have installed the Python environment and pip. Next, you can use pip to install Django. Enter the following command in the terminal (or console):

pip install Django

Once the installation is complete, you can check the Django version by entering the following command:

django-admin --version

If the installation is successful, the version of Django should be displayed Number.

Next, you need to create a Django project and set up a virtual environment. A virtual environment isolates the dependencies required by a project so that they do not interfere with each other. You can use the following command:

mkdir myproject
cd myproject
python -m venv myprojectenv

where "myproject" is the name of your project and "myprojectenv" is the name of the virtual environment. Next, you need to activate the virtual environment, use the following command:

source myprojectenv/bin/activate

You can see the name of the virtual environment in front of the command prompt in the terminal, indicating that the activation has been successful. Now you can run Django commands in the virtual environment.

2. Create a Django application

Before creating a Django application, you need to make sure you have entered your Django project directory. You can create a new Django application using the following command:

python manage.py startapp myapp

where "myapp" is the name of your application and it will create a folder within the "myproject" project. In this folder, you can write your application code, define the database model, handle views and routing, etc.

After you create your application, you need to add it to your Django project's configuration. Open the "settings.py" file in the "myproject" directory and add your application name in the "INSTALLED_APPS" list:

INSTALLED_APPS = [
    # ...
    'myapp',
]

3. Define the database model

Django provides a built-in The ORM (Object Relational Mapping) framework can map Python objects into database tables. In order to define a database model, you need to create a file called "models.py" in your application folder. In this file, you can define your database tables and properties as follows:

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

    def __str__(self):
        return self.name

class Book(models.Model):
    name = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

In the above model definition, "Author" and "Book" are the names of the database tables respectively. Each model definition inherits from "models.Model" and defines its properties. In this example, "Author" has "name" and "email" attributes, and "Book" has "name" and "author" attributes.

4. Routing and Views

In Django, route resolution is used to identify the logic of a specific URL request. You need to create a file called "urls.py" in your application folder and define the routes in it as follows:

from django.urls import path
from . import views

urlpatterns = [
    path('books/', views.book_list, name='book_list'),
    path('books/<int:pk>/', views.book_detail, name='book_detail'),
]

In the above route definition, the "path" function determines the URL request The path, specifies the name of the view function, and defines the logic that the view function will execute when an incoming request is made. In this example, "book_list" and "book_detail" are custom view functions and should be defined accordingly in the application folder.

5. Templates and static files

Django provides built-in template support that can be used to separate application logic and front-end display. Create a folder called "templates" within your application folder where Django will look for and render template files. You can use the template engine in the view function to render the template as follows:

from django.shortcuts import render
from .models import Book

def book_list(request):
    books = Book.objects.all()
    return render(request, 'books/book_list.html', {'books': books})

In the above example, we retrieve all the book records from the database and pass them as context variables to the rendered template. In the "render" function we specify the template name and include the context variables in a dictionary.

In Django, static files (such as CSS, JavaScript, and images) are usually stored in a separate folder named "static". You can create this folder within your application folder and place static files in it. In the template, you can use the following code to reference static files:

<link rel="stylesheet" href="{% static 'css/styles.css' %}">

6. Management page

Django provides a powerful management interface for managing application data. The administrator interface can be used to add, edit and delete data without writing any code. In order to enable the admin interface, you need to register your model in "myapp/admin.py".

from django.contrib import admin
from .models import Author, Book

admin.site.register(Author)
admin.site.register(Book)

7. Summary

This article provides the basic knowledge and skills of Django programming to help you get started and start developing web applications. Django is not only a powerful tool for building efficient and secure web applications, it also provides many built-in features and plug-ins to help you quickly develop your applications. Whether you are a beginner or an experienced developer, mastering Django programming will bring you more opportunities and challenges.

The above is the detailed content of Django Programming Guide: The Road to Mastery in Python Web 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