我有两个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'Автор записи'
答案 0 :(得分:0)
我解决了以下问题:
更改页面模型中的记录字段
record = SortableForeignKey(Record,verbose_name =u'Запись',related_name ='pages',null = True,blank = True,默认=无)
将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()