1👍
You can make use of Django’s Select2 widget and customize it to handle the creation of new Instructions objects:
Create a custom form field that extends the ModelChoiceField and overrides the prepare_value method. This method will handle cases where the value is a string (representing a new Instruction) instead of an ID:
from django import forms
class TaggableModelChoiceField(forms.ModelChoiceField):
def prepare_value(self, value):
# If value is a string, assume it is a new Instruction and return
it as the value
if isinstance(value, str):
return value
return super().prepare_value(value)
Update the TaskInlineModelForm to use the TaggableModelChoiceField for the instructions field:
from django.contrib.admin.widgets import AutocompleteSelect
class TaskInlineModelForm(forms.ModelForm):
instructions = TaggableModelChoiceField(
queryset=Instructions.objects.all(),
widget=AutocompleteSelect(
Task.instructions.field,
admin_site=admin.site,
attrs={"data-tags": "true"},
),
)
class Meta:
model = Task
fields = "__all__"
TaggableModelChoiceField should override the default behavior of the field and allow it to handle both existing Instruction objects (using their IDs) and new Instruction values (as strings). When a string value is encountered, it should be treated as a new Instruction. If the value does not exist yet, it should be saved as a new instruction.
Hope this helps