[Django]-Django Form Automatically select first option if only one choice available

2👍

What about using this :

Your_Dropdown = forms.TypedChoiceField(choices=your choises, initial='FIRST_OPTION')

As shown in documentation: Here

1👍

I don’t think any explanation is required, have a look at following code

post_type_choices = (
    ('article', 'article'),
    ('tip', 'tip'),
    ('snippet', 'snippet'),
)


class Post(models.Model):
    post_type = models.CharField(
        max_length=10, choices=post_type_choices,default='article')

1👍

I did it in the get_form() like this:

    def get_form(self, form_class=form_class):
        form = super(WPWeekSubjectCreateView, self).get_form(form_class)
        ....
        subjects = Subject.objects.filter(
            schoolyear=schoolyear,
            pk__in=subject_bearings,
            lesson__teachers=teacher
        ).order_by('abbreviation').distinct()

        form.fields['subject'].queryset = subjects
        if subjects.count() == 1:
            form.fields['subject'].initial = subjects.first()
    
        return form

Leave a comment