[Fixed]-How to pre-select dropdown on Django?

1👍

Did you try to set the default argument in the situacao field.

situacao = models.CharField("Situação", max_length=30, choices=Choices.situacao, default=Choices.situacao[0][1], blank=True, null=True)

0👍

Dynamically you can set .initial = in Form’s __init__:

class FormChooseRegulation(forms.Form):
    regulation = forms.ChoiceField(required=True, label=_('Regulation'))

    def __init__(self, *args, **kwargs):
        regulations = kwargs.pop('regulations', ())
        regulation_last = kwargs.pop('regulation_last', None)
        super().__init__(*args, **kwargs)
        self.fields['regulation'].choices = regulations
        if regulation_last:
            self.fields['regulation'].initial = regulation_last

called in view:

def regulation_selection(request):
    regulations = list(Regulation.objects.values_list('id', 'label'))
    form_regulation = FormChooseRegulation(
                regulations=regulations,
                regulation_last=request.session.get('regulation_id')
            )
👤mirek

Leave a comment