I have a simple app (about QR codes) in which I have two models. The first one is for defining the QR Code and the second one is for giving it a function. (For those wondering: I split it up into two models because our QR codes are complex and sometimes lack functions and are read-only. I wanted to keep our database as normalized as possible).
Here is the model (models.py):
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.utils.translation import ugettext_lazy as _
from core.behaviors import QRCodeable, UniversallyUniqueIdentifiable
from core.utils import QR_CODE_FUNCTIONS
from model_utils.fields import StatusField
from model_utils.models import SoftDeletableModel, TimeStampedModel
QR_CODE_PREFIX = "QR Code"
QR_CODE_FUNCTION_PREFIX = "Function"
QR_CODE_FUNCTION_MIDFIX = "for"
class QRCode(
UniversallyUniqueIdentifiable,
SoftDeletableModel,
TimeStampedModel,
models.Model
):
@property
def function(self):
try:
return self.qrcodefunction.qr_code_function
except ObjectDoesNotExist:
return ""
class Meta:
verbose_name = _('QR code')
verbose_name_plural = _('QR codes')
def __str__(self):
return f'{QR_CODE_PREFIX} {self.uuid}'
class QRCodeFunction(
UniversallyUniqueIdentifiable,
SoftDeletableModel,
TimeStampedModel,
QRCodeable,
models.Model
):
QR_CODE_FUNCTIONS = QR_CODE_FUNCTIONS
qr_code_function = StatusField(choices_name="QR_CODE_FUNCTIONS")
class Meta:
verbose_name = _('QR code function')
verbose_name_plural = _('QR code functions')
def __str__(self):
return f'{QR_CODE_FUNCTION_PREFIX} {self.qr_code_function} {QR_CODE_FUNCTION_MIDFIX} {self.qr_code}'
The mixin QRCodeable is an abstract base class which gives the function a OneToOne relation to the QR code. The mixin UniversallyUniqueIdentifiable gives it a uuid.
Anyways, I now want to be able to create QR codes with functions within the Django admin. So I wrote my own admin class (admin.py):
from django.contrib import admin
from .models import QRCode, QRCodeFunction
class QRCodeFunctionInline(admin.TabularInline):
model = QRCodeFunction
extra = 0
@admin.register(QRCode)
class QRCodeAdmin(admin.ModelAdmin):
save_on_top = True
search_fields = ['qrcodefunction__qr_code_function']
list_display = (
'__str__',
'function',
)
inlines = [
QRCodeFunctionInline,
]
This code results in the following admin interface:
If I now click on add another QR code function
, choose a function and hit save, the new instance of QR code function does NOT get created! Why is that? How can I write this model admin so that I can create functions for the QR code in the QR codes admin?