Я работаю над интерфейсом администратора Django, в котором определенные поля (в частности, флаги статуса проверки, такие как is_pending_review_section_title_en и is_pending_review_section_title_uk) должны быть помечены как доступные только для чтения в интерфейсе администратора, но при этом обновляться программно при изменении контента. p>
Я реализовал логику для динамического определения полей как доступных только для чтения с помощью метода get_readonly_fields внутри встроенного класса администратора (SectionInline). Хотя поля корректно отображаются в интерфейсе как доступные только для чтения, проблема возникает, когда я пытаюсь обновить эти поля в методе save_model класса PageAdmin (или даже в формах). Флаги в коде установлены правильно, но они не сохраняются в базе данных после сохранения.
Вот краткое изложение того, что я пробовал:
1. Marked fields as read-only using get_readonly_fields — This works for the admin UI.
2. Tried updating the fields programmatically inside save_model in the PageAdmin class and verified the values through logging. The flags are set to True, but after saving, the values in the database remain unchanged.
3. Commented out form save logic to check if it’s interfering with saving, but the issue persists.
4. Ensured flags are not present in forms to avoid user interaction.
Что может быть причиной неправильного сохранения полей, хотя они обновляются программно в коде? Есть ли какие-либо особые соображения по обновлению полей, доступных только для чтения, в администраторе?
class SectionInline(nested_admin.NestedStackedInline):
model = Section
extra = 0
inlines = [ContentInline]
fields = (
"section_title_en",
"section_title_uk",
"is_pending_review_section_title_en",
"is_pending_review_section_title_uk",
)
def get_readonly_fields(self, request, obj=None):
readonly_fields = super().get_readonly_fields(request, obj)
readonly_fields += (
"is_pending_review_section_title_en",
"is_pending_review_section_title_uk",
)
return readonly_fields
class PageAdmin(nested_admin.NestedModelAdmin):
list_display = ("menu_title", "slug", "created_at")
list_filter = ("created_at",)
search_fields = ("menu_title", "slug")
inlines = [SectionInline]
fields = ("menu_title_en", "menu_title_uk", "created_at")
def save_model(self, request, obj, form, change):
try:
page_snapshot = PageSnapshot.objects.get(original_page=obj)
logger.debug(f"Snapshot exists for Page - {obj.menu_title}")
except PageSnapshot.DoesNotExist:
page_snapshot = None
if not page_snapshot:
logger.debug(f"Snapshot DOES NOT exist for {obj.menu_title}")
self.create_snapshot(obj)
for section in obj.sections.all():
section_snapshot = None
if page_snapshot:
try:
section_snapshot = SectionSnapshot.objects.get(
original_section=section, page_snapshot=page_snapshot
)
logger.debug(f"section_snapshot found for {section.section_title}")
except SectionSnapshot.DoesNotExist:
pass
if section_snapshot:
if section.section_title_en != section_snapshot.section_title_en:
section.is_pending_review_section_title_en = True
if section.section_title_uk != section_snapshot.section_title_uk:
section.is_pending_review_section_title_uk = True
else:
if section.section_title_en:
logger.debug(f"Setting section_title_en review flag")
section.is_pending_review_section_title_en = True
if section.section_title_uk:
section.is_pending_review_section_title_uk = True
section.save()
logger.debug(
f"After saving: section.is_pending_review_section_title_en for {section.section_title_en}: {section.is_pending_review_section_title_en}"
)
super().save_model(request, obj, form, change)
def create_snapshot(self, page_obj):
if PageSnapshot.objects.filter(original_page=page_obj).exists():
return
page_snapshot = PageSnapshot.objects.create(
original_page=page_obj,
menu_title_en=page_obj.menu_title_en,
menu_title_uk=page_obj.menu_title_uk,
slug=page_obj.slug,
)
for section in page_obj.sections.all():
section_snapshot = SectionSnapshot.objects.create(
original_section=section,
page_snapshot=page_snapshot,
section_title_en=section.section_title_en,
section_title_uk=section.section_title_uk,
is_published=section.is_published,
)
for content in section.contents.all():
content_snapshot = None
if section_snapshot:
try:
content_snapshot = ContentSnapshot.objects.get(
original_content=content, section_snapshot=section_snapshot
)
except ContentSnapshot.DoesNotExist:
pass
if content_snapshot:
if content.text_en != content_snapshot.text_en:
content.is_pending_review_text_en = True
if content.text_uk != content_snapshot.text_uk:
content.is_pending_review_text_uk = True
if content.char_en != content_snapshot.char_en:
content.is_pending_review_char_en = True
if content.char_uk != content_snapshot.char_uk:
content.is_pending_review_char_uk = True
if content.url != content_snapshot.url:
content.is_pending_review_url = True
if content.image != content_snapshot.image:
content.is_pending_review_image = True
if content.file != content_snapshot.file:
content.is_pending_review_file = True
else:
if content.text_en:
content.is_pending_review_text_en = True
if content.text_uk:
content.is_pending_review_text_uk = True
if content.char_en:
content.is_pending_review_char_en = True
if content.char_uk:
content.is_pending_review_char_uk = True
if content.url:
content.is_pending_review_url = True
if content.image:
content.is_pending_review_image = True
if content.file:
content.is_pending_review_file = True
content.save()
admin.site.register(Page, PageAdmin)
Подробнее здесь: https://stackoverflow.com/questions/791 ... not-saving
Проблема с обновлением полей, доступных только для чтения, в администраторе Django: флаги не сохраняются. ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Есть ли способ определить флаги в Java и запустить код, только если эти флаги определены?
Anonymous » » в форуме JAVA - 0 Ответы
- 38 Просмотры
-
Последнее сообщение Anonymous
-