Consider these pseudo models:
class Category(models.Model):
name = models.CharField()
class Product(models.Model):
name = models.CharField()
code = models.CharField()
category = models.ForeignKey(Category)
price = models.DecimalField()
stock = models.IntegerField()
class AlternativeProduct(Product):
original_product = models.ForeignKey(Product, related_name="alternative", editable=False)
I want to use inlines to be able to quickly add a product and its alternative option without typing duplicate data (ONLY code, stock and price differentiate).
admin.py
class AlternativeProductInline(admin.TabularInline):
model = AlternativeProduct
formset = AlternativeProductInlineFormset
fk_name = "original_product"
fields = ["code", "price", "in_stock"]
max_num = 1
extra = 0
class ProductAdmin(admin.ModelAdmin):
form = ProductAdminForm
inlines = [AlternativeProductInline]
Ofcourse this will raise ValidationError, because AlternativeProduct is missing a category.
Now I could setup a default value to fix that:
class Product(models.Model):
name = models.CharField()
code = models.CharField()
category = models.ForeignKey(Category, default=1)
price = models.DecimalField()
stock = models.IntegerField()
But besides the fact this id might not exist it still needs to be corrected. Is there any other way (besides Javascript) to copy the category value of the genuine product to the alternative inline product ‘under the hood‘
I have tried to change the admin_view, but it gets hackish, perhaps a custom view would be a nice solution although javascript is a less time consuming approach.
Javascript does seem to be the easy approach to achieve this.