


Backend management system skills in the Django framework (Part 2)
Backend management system skills in the Django framework (Part 2)
In the previous article, we introduced some backend management system skills in the Django framework, such as how to customize the background page layout, how to Custom filters, how to customize actions, etc. This article will continue to introduce more practical tips to help you better use the Django framework.
- How to deal with the default value of ForeignKey in Model
In Django Model, ForeignKey is a very practical field type. However, when we create a new Model instance, the ForeignKey type field needs to specify an instance of the related Model in order to be saved successfully. If not specified, NULL values will be saved by default. In some cases, we may want the ForeignKey type field to be saved in a default association instance. In this case, we can use Django's get_or_create method.
For example, we have a Product Model and define a ProductCategory ForeignKey field for it. We hope that when we create a new Product instance, it will automatically associate a default Category instance. You can add the following code to the Model :
class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(ProductCategory, default=get_default_category) def get_default_category(): """ 返回默认的ProductCategory实例或者创建一个新的实例 """ category, _ = ProductCategory.objects.get_or_create(name='Default Category') return category
In this way, when we create a new Product instance, a ProductCategory instance named "Default Category" will be automatically associated by default.
- How to restrict a Model in the background management system to only create one instance
In some cases, we may want a Model to create only one instance, such as in a website Global Settings. At this time, you can use Django's SingletonModel library, which provides a BaseSingletonModel that allows us to easily convert any Model to a Singleton Model.
For example, we have a GlobalSettings Model and hope that it can only create one instance. It can be defined like this:
from singleton_models.models import SingletonModel class GlobalSettings(SingletonModel): site_name = models.CharField(max_length=100, default='') site_url = models.URLField(default='') # 其他全局设置字段
After defining it, in the background management system, we can only create and edit A GlobalSettings instance.
- How to add custom middleware for the background management system
In the Django framework, middleware is an interceptor used to process requests and responses. It can handle the request or response before the request reaches the view function, after the view function handles the request, and before the response is sent to the client. Among them, adding custom middleware to the background management system allows us to easily intercept and process the administrator's operations.
For example, if we want the administrator to need to enter a secondary confirmation password when making certain modification operations, we can add the following code to the settings.py file of the Django project:
MIDDLEWARE = [ # 默认的中间件 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # 自定义中间件 'myapp.middleware.ConfirmPasswordMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CONFIRMED_ACTIONS = ( 'myapp.views.EditProductView', 'myapp.views.DeleteProductView', ) class ConfirmPasswordMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # 根据请求的URL判断是哪个视图函数,如果是CONFIRMED_ACTIONS中的视图函数,需要做二次确认 view_func = resolve(request.path_info).func if view_func and view_func.__module__ + "." + view_func.__name__ in CONFIRMED_ACTIONS: if not request.session.get('password_confirmed', False): # 没有输入二次确认密码,跳转到输入页面 return redirect(reverse('confirm-password')) response = self.get_response(request) return response
The above code , we define a ConfirmPasswordMiddleware, which intercepts the request before it reaches the view function and determines whether a secondary confirmation password is required. CONFIRMED_ACTIONS is a list of view functions that require secondary confirmation. We can add or delete them as needed. In the view function, we can query whether the current user has entered the secondary confirmation password through request.session.get('password_confirmed', False).
- How to add a serializer to the Model of the background management system
In the Django framework, Serializer is a class used to convert the Model into a dictionary or JSON format. Adding a serializer to the backend management system allows us to easily convert the Model to JSON format and output it.
For example, we have a Product Model and want to convert it to JSON format and output it in the background management system. It can be defined like this:
from django.contrib import admin from django.core.serializers import serialize from django.http import HttpResponse class ProductAdmin(admin.ModelAdmin): # 列表视图显示的字段列表 list_display = ('name', 'price', 'category') # 自定义action函数 def export_as_json(self, request, queryset): response = HttpResponse(content_type="application/json") serializers.serialize("json", queryset, stream=response) return response export_as_json.short_description = "导出为JSON" # 自定义函数按钮 change_list_template = 'admin/myapp/product/list.html' def get_urls(self): urls = super().get_urls() my_urls = [ path('my_view/', self.my_view), ] return my_urls + urls def my_view(self, request): data = serialize('json', Product.objects.all()) return JsonResponse(data, safe=False) admin.site.register(Product, ProductAdmin)
In the above code, we add An export_as_json function is provided, which can convert the currently selected Model instance into JSON format and output it to the client. At the same time, we also added a my_view function to ProductAdmin, which can directly query all Model instances and convert them into JSON format output.
Summary
The background management system of the Django framework is an important tool for developing web applications. It provides many ready-made functions that allow us to easily manage Model instances, batch modifications and deletions. In this article, we introduce some practical tips for the Django framework backend management system, including how to handle the default value of ForeignKey in the Model, how to limit a Model in the backend management system to only create one instance, and how to add customization to the backend management system. Define middleware and how to add serializers to the Model of the backend management system. Through the use of these techniques, we can better use the background management system of the Django framework.
The above is the detailed content of Backend management system skills in the Django framework (Part 2). For more information, please follow other related articles on the PHP Chinese website!

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools