Default value for ForeignKey field in django admin panel

I have two django Models: PageModel and RecordModel. They are registered in django admin panel. I want automatically create RecordModel object and assign it to (object of PageModel).record field if record is not selected in process of Page creation. (Django Admin – Add Page form) I tried to create form and used clean_record() method, but that not work. (debugger is not stopped there) How can i solve the problem?

Models (Sortable and SortableAdmin classes are part of adminsortable (https://github.com/iambrandontaylor/django-admin-sortable), but I think it does not really matter):

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)

Admin:

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'Автор записи'


Source: python

Leave a Reply