我正在通过Django管理员生成静态网站版本。需要一些时间,所以我决定使用Celery。但这引发了我这个错误:
EncodeError at /admin/pages/project/
Object of type Project is not JSON serializable
如何使用celery在Django管理面板中将命令作为操作调用?
admin.py
from .tasks import command_task
@admin.register(Project)
class ProjectAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'updated', 'created', 'is_active')
actions = ['export_to_static_version']
def export_to_static_version(self, request, queryset):
if len(queryset) > 0:
project = queryset[0]
command_task.delay(project)
models.py
class Project(models.Model):
dev_list = ['1', '2', '3', '4']
title = models.CharField(max_length=100)
author = models.CharField(choices=dev_list), max_length=100, blank=True)
comment = models.TextField(blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(null=False, default=False)
设置
CELERY_BROKER_URL = 'amqp://localhost'
CELERY_RESULT_BACKEND = 'amqp://localhost'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Europe/Berlin'
CELERY_BEAT_SCHEDULE = {}
celery.py
import os
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'basic.settings.development')
app = Celery('basic')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
tasks.py
from celery import task
from django.core.management import call_command
@task
def command_task(project):
call_command('generate_static_website', id=project.id)