Django 管理面板中 ForeignKey 字段的默认值

Default value for ForeignKey field in django admin panel

我有两个 Django 模型:PageModel 和 RecordModel。他们在 django 管理面板中注册。如果在页面创建过程中未选择记录,我想自动创建 RecordModel 对象并将其分配给(PageModel 的对象).record 字段。 (Django Admin - 添加页面表单)我尝试创建表单并使用 clean_record() 方法,但这不起作用。 (调试器不止于此)我该如何解决这个问题?

模型(Sortable 和 SortableAdmin 类 是 adminsortable (https://github.com/iambrandontaylor/django-admin-sortable) 的一部分,但我认为这并不重要):

class Record(Sortable):
    """
    Запись в книге почетных гостей
    """
    class Meta(Sortable.Meta):
        verbose_name = u'Запись'
        verbose_name_plural = u'Записи'

    author = models.CharField(verbose_name=u'Автор', max_length=255, unique=False, blank=False,
                              default=author_default)

    def __unicode__(self):
        return u'Запись {} ({})'.format(self.id, self.author)


class Page(Sortable):
    """
    Страница книги почетных гостей
    """

    class Meta(Sortable.Meta):
        verbose_name = u'Страница'
        verbose_name_plural = u'Страницы'

    record = SortableForeignKey(Record, verbose_name=u'Запись', related_name='pages', blank=False, default=None)
    image = models.ImageField(verbose_name=u'Картинка',
                              upload_to='pages',
                              default='',
                              help_text=u'Размер файла - до 10 MB. Формат PNG.',
                              validators=[ImageValidator(formats=['PNG'], max_size=10000000)])
    updated = models.DateTimeField(verbose_name=u'Обновление', auto_now=True, null=True,
                                   help_text=u'Время последнего изменения страницы на сервере')

    def __unicode__(self):
        return u'Страница {} ({})'.format(self.id, self.image)

管理员:

class PageInline(SortableTabularInline):
    model = Page


@admin.register(Record)
class RecordAdmin(SortableAdmin):
    list_display = ['author', 'pages_count']

    inlines = [PageInline]

    fields = ['author']

    def pages_count(self, object):
        return object.pages.count()
    pages_count.short_description = u'Количество страниц'
    pages_count.allow_tags = False


class PageAdminForm(forms.ModelForm):
    def clean_record(self):
        return self.cleaned_data["record"]


@admin.register(Page)
class PageAdmin(SortableAdmin):
    list_display = ['__unicode__', 'image', 'author', 'updated']

    form = PageAdminForm

    readonly_fields = ['updated']

    def get_fields(self, request, obj=None):
        if obj:
            return super(PageAdmin, self).get_fields(request, obj)
        else:
            return ['record', 'image']

    def author(self, page):
        return page.record.author
    author.allow_tags = False
    author.short_description = u'Автор записи'

我解决问题如下:

  1. 更改页面模型中的记录字段

    record = SortableForeignKey(Record, verbose_name=u'Запись', related_name='pages', null=True, blank=True, default=None)

  2. 将 save_model() 方法添加到 PageAdmin

    def save_model(self, request, obj, form, change): 如果 obj.record 是 None: record = Record.objects.create(author=BookConfiguration.get_solo().record_author_default + ' (' + timezone.localtime(timezone.now()).strftime('%Y-% m-%d %H:%M:%S') + ')') record.save()