简体   繁体   中英

Django Form Automatically select first option if only one choice available

Is there an easy way to select the first option of a dropdown in a Django form, in cases where there is only one option available?

With easy I mean a solution that doesn't require defining an own widget, which would be quite repetitive to change in all our (model) forms.

Update because it seems like the initial question was unclear:

I want the initital option only to be selected if there is one option available. And the the way to do that is non-obvious to me, if the options are foreign key references to another model:

class Category(models.Model):
     name = CharField(...)

class Post(models.Model):
    category = ForeignKey(Category)

class PostForm(forms.ModelForm):
    class Meta:
        fields = '__all__'
    [...]

Now I want the category field in the PostForm to be autoselected to the first category, if only one instance is present in the database and be -------- if there a two or more categories

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')

What about using this :

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

As shown in documentation: Here

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM