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 (, 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,

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

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'Картинка',
                              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.image)


class PageInline(SortableTabularInline):
    model = Page

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"]

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)
            return ['record', 'image']

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

Source: python

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.