Prvz
Prvz

Reputation: 203

Django - admin related model editing

I'm trying to resolve something and i'm hope for your help

there is 2 models:

def BigBox(models.Model):
    title = textfield
    date = datetimefield
    author = foreignkey(user)
    # other fields etc.

def SmallBox(models.Model):
    title = textfield
    contained_in = foreignkey(BigBox)
    # little box that can be only in big box

I have a way to view SmallBoxes in readonly_fields of BigBox adminModel but have no way to edit or creating new at this point.


I need to make (all that is written below apply to the admin.ModelAdmin):

When you edit/creating BigBox, need to be able to create new related SmallBoxes inside.

That means that every BigBox always contains at least one SmallBox and every SmallBox always in anyof BigBox.

Need to specify way of creating SmallBoxes just inside BigBox.

Upvotes: 0

Views: 945

Answers (2)

Prvz
Prvz

Reputation: 203

I found solution with just better searching.

This called 'inlines' https://docs.djangoproject.com/en/2.0/intro/tutorial07/#adding-related-objects

Upvotes: 1

coderDude
coderDude

Reputation: 904

I think the best way to achieve this would be to use signals.

post_save() signal to be specific. After declaring both model classes, define a method that checks if BigBox set contains a SmallBox instance. If not , then create an instance of SmallBox and attach to BigBox instance.

Reference : https://docs.djangoproject.com/en/dev/ref/signals/#post-save

Example : https://simpleisbetterthancomplex.com/tutorial/2016/07/28/how-to-create-django-signals.html

The above example shows how to define a function and attach to a model using post_save.connect() or by using @receiver(post_save, sender=BigBox) decorator over the function

Upvotes: 1

Related Questions