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.
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.
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.
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).
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!