field choices() as queryset?

前端 未结 4 1872
难免孤独
难免孤独 2020-12-09 10:46

I need to make a form, which have 1 select and 1 text input. Select must be taken from database. model looks like this:

class Province(models.Model):
    nam         


        
4条回答
  •  盖世英雄少女心
    2020-12-09 11:42

    the two solutions given by maersu and Yuji 'Tomita' Tomita perfectly works, but there are cases when one cannot use ModelForm (django3 link), ie the form needs sources from several models / is a subclass of a ModelForm class and one want to add an extra field with choices from another model, etc.

    ChoiceField is to my point of view a more generic way to answer the need.

    The example below provides two choice fields from two models and a blank choice for each :

    class MixedForm(forms.Form):
        speaker = forms.ChoiceField(choices=([['','-'*10]]+[[x.id, x.__str__()] for x in Speakers.objects.all()]))
        event = forms.ChoiceField(choices=( [['','-'*10]]+[[x.id, x.__str__()] for x in Events.objects.all()]))
    

    If one does not need a blank field, or one does not need to use a function for the choice label but the model fields or a property it can be a bit more elegant, as eugene suggested :

    class MixedForm(forms.Form):
        speaker = forms.ChoiceField(choices=((x.id, x.__str__()) for x in Speakers.objects.all()))
        event = forms.ChoiceField(choices=(Events.objects.values_list('id', 'name')))
    

    using values_list() and a blank field :

        event = forms.ChoiceField(choices=([['','-------------']] + list(Events.objects.values_list('id', 'name'))))
    

    as a subclass of a ModelForm, using the one of the robos85 question :

    class MixedForm(ProvinceForm):
        speaker = ...
    

提交回复
热议问题