Django异步请求和后台管理实战
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import gettext
from .models import User
from .tasks import send_confirmation_email
class UserAdmin(BaseUserAdmin):
ordering = ['id']
list_display = ['email', 'username', 'is_staff']
fieldsets = (
(None, {'fields': ('email', 'password')}),
(gettext('Personal info'), {'fields': ('username',)}),
(gettext('Permissions'), {
'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
}),
(gettext('Important dates'), {'fields': ('last_login',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2', 'is_staff', 'is_superuser'),
}),
)
search_fields = ('email',)
list_filter = ('is_staff', 'is_superuser', 'is_active')
def save_model(self, request, obj, form, change):
if not obj.id:
send_confirmation_email.delay(obj.email)
super().save_model(request, obj, form, change)
admin.site.register(User, UserAdmin)
这段代码定义了一个UserAdmin类,继承自BaseUserAdmin,并对User模型的后台管理界面进行了定制。在保存模型时,如果User对象是新创建的(not obj.id
),则会异步调用send_confirmation_email
任务来发送确认邮件。这是一个很好的实践,展示了如何在Django中结合异步任务处理特定的业务逻辑。
评论已关闭