Here is how my model and admin looks like: Model
class Event(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=120)
description = models.TextField(default="", blank=True)
start = models.DateTimeField(default=datetime.now)
end = models.DateTimeField(blank=True, null=True)
parent_event = models.ForeignKey(
to="Event", on_delete=models.CASCADE, blank=True, null=True)
Admin
EVENT_DISPLAYABLE_FIELDS = ["title", "start", "end"]
# Will display and allow adding inline sub events
# in tabular format
class SubEventInline(admin.TabularInline):
model = Event
# Do not add empty extra inlines
extra = 0
# Will allow only the fields listed below
# to be displayed and edited
fields = EVENT_DISPLAYABLE_FIELDS
# Will allow navigating to its edit page
show_change_link = True
# Will display the Event edit page on admin site
class EventAdmin(admin.ModelAdmin):
# Will only display the fields listed below
# on the main events page
list_display = EVENT_DISPLAYABLE_FIELDS
list_display.append('preview')
# Enables sub events to be displayed or allowed
# to be added in the current event's edit page
inlines = [
SubEventInline,
]
def preview(self, event):
url = reverse('events', kwargs={'id': event.id})
return format_html('<a class="button" href="{}">Preview</a>', url)
preview.short_description = 'Preview Event'
preview.allow_tags = True
The above correctly displays the button on the list display view, but when clicking on any event to navigate to it's change/edit page, django throws an error:
django.core.exceptions.FieldError: Unknown field(s) (preview) specified for Event
Please help me find out what am I missing here?
I tried using exclude in TabularInline but Django then throws a different error message saying
Keyerror "preview"
I also tried adding a new non-persistent field to the event model but it did not work.