[Python] Django Rest viewsets.ModelViewSet form view dynamic update choices list field from...

Discussão em 'Python' iniciado por Stack, Julho 29, 2025.

  1. Stack

    Stack Membro Participativo

    file models.py

    ANIMATIONS_ACTIONS = (
    ('0', _('Stop animations')),
    ('1', _('Start animations')),
    ('2', _('Restart animations')),
    ('3', _('Suspend animations')),
    ('4', _('Unload animation module')),
    ('5', _('Load animation module')),
    ('6', _('Reload animation module')),
    ('7', _('Launch animation module')),
    ('8', _('Display animation module')),
    )

    class Animation(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    modified_at = models.DateTimeField(auto_now=True, editable=False)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL,
    null=True, db_index=True, editable=False,
    on_delete=models.SET_NULL, related_name="%(class)s_created")
    modified_by = models.ForeignKey(settings.AUTH_USER_MODEL,
    null=True, db_index=True, editable=False,
    on_delete=models.SET_NULL, related_name="%(class)s_modified")
    animation_module_name = models.CharField(max_length=128, blank=True)
    animation_action = models.CharField(max_length=1, choices=ANIMATIONS_ACTIONS)

    class Meta:
    """Class Meta"""
    verbose_name = _("Animation's Action")
    verbose_name_plural = _("Admin Animation")
    ordering = ["-created_at"]`


    file serializers.py

    class AnimationSerializer(serializers.ModelSerializer):
    class Meta:
    model = Animation
    fields = '__all__'
    def create(self, validated_data):
    match validated_data['animation_action']:
    case '0':
    …
    case '1':
    …
    case '2':
    …
    case '3':
    …
    case '4':
    if validated_data['animation_module_name']:
    …
    case '5':
    if validated_data['animation_module_name']:
    …
    case '6':
    if validated_data['animation_module_name']:
    …
    case '7':
    if validated_data['animation_module_name']:
    …
    case '8':
    if validated_data['animation_module_name']:
    …
    return super().create(validated_data)


    file views.py

    class AnimationViewSet(viewsets.ModelViewSet):
    serializer_class = AnimationSerializer
    queryset = Animation.objects.all()


    How can I update the animation_module_name field choice list (return function with the selected value of the animation action) to reflect the value of the animation_action field change in the view created? [​IMG] Like JavaScript onchange does ...

    I tried a lot of things, but I need to post the result before Django does the things. I need to update the widget with the select list choice from animation_action.

    Continue reading...

Compartilhe esta Página