make some model field conditionally visible in django

I have two field in my django model they should be editable only if user have selected 'type' as 'Dimention' otherwise they should not be visible to user.

My model is look like this code

from django.db import models

class Configuration(models.Model):

   name = models.CharField(max_length=30)
   user_defined_name = models.CharField(max_length=50)
   FieldTypes = (('aD', 'Dimension'), ('aM', 'Measure'))
   type = models.CharField(max_length=11, choices=FieldTypes)
   is_key = models.BooleanField(default=False, editable=False)
   unit = models.CharField(max_length=30, null=True, blank=True, editable=False)

   def __str__(self):

I know it is possible by using JavaScript but, I don't want to write html or js myself,Thus Can't use JavaScript for doing this.

1 answer

  • answered 2018-04-17 05:58 rtindru

    A pure Django-only way to achieve this is to simply reset the fields from your ModelForm if type is not equal to Dimension. This will appear like magic/unintended behavior; so be careful of the implementation.

    For example (assuming you are using the admin interface: the same is valid for a custom ModelForm View):

    class ConfigurationAdmin(admin.ModelAdmin):
        def save_model(self, request, obj, form, change):
            #  At this point; the object already has the new values set; we will have to reset as needed
            conditional_editable_fields = ['is_key', 'unit']
            config_type = form.cleaned_data.get('type')
            if config_type != 'aD':
                for field in conditional_editable_fields:
                    if field in form.changed_data:  # The value has been changed by the user
                        setattr(obj, field, form.initial.get(field))  # Set the initial value
                        self.message_user(request, "Cannot edit field: {}; value has been reset".format(field), messages.WARNING)  # Inform the user that we reset the value
            return super(ConfigurationAdmin, self).save_mode(request, obj, form, change)