How to control available fields using Django Admin based on selected type ?

I have a model MenuResource which has 3 types: resource with no link, resource with internal page, resource with custom link.
I would like to use Django Admin to create MenuResource objects.
But, depends on the MenuResource type, different attribute should be filled - in case resource_type is INTERNAL PAGE, internal_url_name attribute should be filled and in case resource_type is CUSTOM LINK then external_hyperlink should be filled.
Is there a way I could quickly solve this using Django Admin - so after user selects specific resource_type, A) specific attribute should be presented for him to fill it or B) specific attribute field should be disabled/enabled. How could I do that using Django Admin - both ways A) and B) are fine for me ?

class MenuResourceChoice(models.TextChoices):
    R0 = 'R0', 'NO LINK'
    R1 = 'R1', 'INTERNAL PAGE'
    R2 = 'R2', 'CUSTOM LINK'

class MenuResource(models.Model):
    resource_type = models.CharField(max_length=2, choices=MenuResourceChoice.choices, default=MenuResourceChoice.R0)
    internal_url_name = models.CharField(max_length=30)
    external_hyperlink = models.URLField()

EDIT 1: Also if I have pre-defined buttons to set the type before the form is presented to user - so buttons like “Create Custom Link” and “Create Internal Page” and then depending which button you click, different form is presented to you - this solution is also fine for me if possible.

Thank you.

You can do this through the admin, the question is whether or not you should.

Yes, you can create a custom admin page with some JavaScript to do this. (You might have to do some exploring to understand how to find the components you want to use, but it can be done.)
See the ModelAdmin docs for the fields you can set and the methods you can override in your ModelAdmin class.

However, you can quickly get to the point where it’s a whole lot easier to just create your own view to do this. Don’t just automatically assume that the admin is the fastest/easiest way. And, don’t do this unless the people using this are admin-type people for the site. The admin definitely isn’t a tool for a general user.

Ken

1 Like