1

I'm working on legacy code which is in Django (1.11)

I have a model A, with attributes:

Model_A:
  Name (NOT NULL)
  City (NOT NULL)
  FieldX (Nullable) - CharField

And a model B, with attributes:

Model_B:
  Name (NOT NULL)
  City (NOT NULL)
  RelatedField (ForeignKey to an instance of Model_A)

Now, When I add a record for Model_A then I may NOT need to fill FieldX.

However, When I add a record for Model_B then I'll have to select an instance of Model_A and then if FieldX of that instance is NULL then I have to fill that as well (make it mandatory).

The form for Model_A is pretty straight forward.

But for Model_B I need a form where:

  1. First an instance of Model_A is selected (Dropdown)
  2. The input box for FieldX of instance selected in 1 is shown (Editable and mandatory to fill, blank=False).
  3. The rest of the fields are shown (Name, City, FieldY).

Can this be done using the admin page? Or will I have to create proper forms and user flow for this?

Naman Chikara
  • 164
  • 14

2 Answers2

1

I have not tested this, but you should be able to do the following:

from django.contrib import admin

class ModelAForm(ModelForm):
    FieldX = CharField(
        required=True
    )

    class Meta:
        model = Model_A
        fields = ['FieldX']

class ModelAInline(admin.StackedInline):
    model = Model_A
    form = ModelAForm

class ModelBAdmin(admin.ModelAdmin):
    inlines = [
        ModelAInline
    ]

admin.site.register(ModelB, ModelBAdmin)
jdaz
  • 5,964
  • 2
  • 22
  • 34
1

For model B I'd override the view and form in order to achieve this in admin site.

model_b_view = ModelBView.as_view()

@admin.register(Model_B)
class Model_B_Admin(admin.ModelAdmin):
    def get_urls(self):
        urls = super().get_urls()
        my_urls = [
            url(r'^add/$', 
                self.admin_site.admin_view(model_b_view)),
        ]
        return my_urls + urls

Where ModelBView is a template view, and you'd have to override get and post of it, In get send all instances of Model_A to template and handle via jquery there.

dunnothat
  • 71
  • 3