Python django.forms 模块,ModelChoiceField() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.ModelChoiceField()

项目:WorldsAtWar    作者:heidi666    | 项目源码 | 文件源码
def __init__(self, world, *args, **kwargs):
        super(Shipaidform, self).__init__(*args, **kwargs)
        fleets = fleet.objects.filter((Q(sector=world.sector)|Q(sector='hangar')), world=world, controller=world)
        techlist = (
            ('freighters', 'Freighters'),
            ('fighters', 'Fighters'),
            ('corvettes', 'Corvettes'),
            ('light_cruisers', 'Light Cruisers'),
            ('destroyers', 'Destroyers'),
            ('frigates', 'Frigates'), 
            ('heavy_cruisers', 'Heavy Cruisers'), 
            ('battlecruisers', 'Battlecruisers'), 
            ('battleships', 'Battleships'),
            ('dreadnoughts', 'Dreadnoughts')
        )
        choicelist = []
        comparisonfleet = fleet()
        for ball in fleets:
            comparisonfleet.merge(ball)
        for field in techlist:
            if comparisonfleet.__dict__[field[0]] > 0:
                choicelist.append(field)
        choicelist = tuple(choicelist)
        self.fields["ship_choice"] = forms.ChoiceField(choices=choicelist)
        self.fields["fleet_choice"] = forms.ModelChoiceField(queryset=fleets)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def formfield(self, **kwargs):
        db = kwargs.pop('using', None)
        if isinstance(self.remote_field.model, six.string_types):
            raise ValueError("Cannot create form field for %r yet, because "
                             "its related model %r has not been loaded yet" %
                             (self.name, self.remote_field.model))
        defaults = {
            'form_class': forms.ModelChoiceField,
            'queryset': self.remote_field.model._default_manager.using(db),
            'to_field_name': self.remote_field.field_name,
        }
        defaults.update(kwargs)
        return super(ForeignKey, self).formfield(**defaults)
项目:pretalx    作者:pretalx    | 项目源码 | 文件源码
def _save_to_answer(self, field, answer, value):
        action = 'pretalx.submission.answer' + ('update' if answer.pk else 'create')
        if isinstance(field, forms.ModelMultipleChoiceField):
            answstr = ', '.join([str(o) for o in value])
            if not answer.pk:
                answer.save()
            else:
                answer.options.clear()
            answer.answer = answstr
            answer.options.add(*value)
        elif isinstance(field, forms.ModelChoiceField):
            if not answer.pk:
                answer.save()
            else:
                answer.options.clear()
            answer.options.add(value)
            answer.answer = value.answer
        elif isinstance(field, forms.FileField):
            if isinstance(value, UploadedFile):
                answer.answer_file.save(value.name, value)
                answer.answer = 'file://' + value.name
            value = answer.answer
        else:
            answer.answer = value
        answer.log_action(action, person=self.request_user, data={'answer': value})
项目:django-rest-search    作者:wemap    | 项目源码 | 文件源码
def get_form_field_schema(field):
    """
    Returns the coreapi schema for the given form field.
    """
    title = force_text(field.label) if field.label else ''
    description = force_text(field.help_text) if field.help_text else ''

    if isinstance(field, forms.BooleanField):
        field_class = coreschema.Boolean
    elif isinstance(field, forms.FloatField):
        field_class = coreschema.Number
    elif isinstance(field, (forms.IntegerField, forms.ModelChoiceField)):
        field_class = coreschema.Integer
    else:
        field_class = coreschema.String

    return field_class(description=description, title=title)
项目:intel-manager-for-lustre    作者:intel-hpdd    | 项目源码 | 文件源码
def _resolve_relation_uris(self, data):
        # We should be working on a copy of the data, since we're
        # modifying it (FormValidation promises not to modify the bundle).
        data = data.copy()

        fields_to_resolve = [k for k, v in self.form_class.base_fields.items()
                             if issubclass(v.__class__, ModelChoiceField)]

        for field in fields_to_resolve:
            if field in data:
                data[field] = self._resolve_uri_to_pk(data[field])

        return data

    # This is pretty much a straight copy of FormValidation's is_valid().
    # It's unfortunate that there's not a cleaner place to hook into the
    # validation processing for subclasses.
项目:the-contract-site    作者:shadytradesman    | 项目源码 | 文件源码
def make_accept_invite_form(invitation):
    class AcceptInviteForm(forms.Form):
        if invitation.as_ringer:
            attending_character = forms.ModelChoiceField(
                queryset=invitation.invited_player.character_set,
                 empty_label="NPC only",
                 help_text="Instead of one of your characters, you will play an NPC",
                 required=False,
                 disabled=True)
        else:
            queryset = ""
            users_living_character_ids = [char.id for char in invitation.invited_player.character_set.all() if not char.is_dead()]
            required_status = invitation.relevant_game.required_character_status
            if required_status == HIGH_ROLLER_STATUS[0][0]:
                queryset = Character.objects.filter(id__in=users_living_character_ids)
            else:
                queryset = Character.objects.filter(id__in=users_living_character_ids).filter(status=invitation.relevant_game.required_character_status)
            attending_character = forms.ModelChoiceField(queryset=queryset,
                                                         empty_label=None,
                                                         help_text="Declare which character you're attending with. Private "
                                                                   "Characters and their powers will be revealed to the "
                                                                   "Game creator if selected.",
                                                         required=True)
    return AcceptInviteForm
项目:a4-meinberlin    作者:liqd    | 项目源码 | 文件源码
def __init__(self, user=None, organisation=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        choices = [(value, string)
                   for value, string in models.RECEIVER_CHOICES
                   if value != models.PLATFORM or (user and user.is_superuser)]
        self.fields['receivers'] = forms.ChoiceField(
            label=_('Receivers'),
            choices=choices,
            widget=forms.RadioSelect(),
        )

        project_qs = Project.objects
        if organisation:
            project_qs = Project.objects.filter(organisation=organisation.id)

        self.fields['project'] = forms.ModelChoiceField(
            label=_('Project'),
            queryset=project_qs,
            required=False, empty_label=None)

        self.fields['organisation'] = forms.ModelChoiceField(
            label=_('Organisation'),
            queryset=Organisation.objects,
            required=False, empty_label=None)
项目:api-django    作者:lafranceinsoumise    | 项目源码 | 文件源码
def __init__(self, *args, poll, **kwargs):
        super().__init__(*args, **kwargs)
        self.poll = poll
        self.helper = FormHelper()

        if 'options' in self.poll.rules and self.poll.rules['options'] == 1:
            self.fields['choice'] = ModelChoiceField(
                label='Choix',
                queryset=poll.options.all().order_by('?'),
                widget=RadioSelect,
                required=True,
                empty_label=None,
                initial=None,
            )
        else:
            self.fields['choice'] = ModelMultipleChoiceField(
                label='Choix',
                queryset=poll.options.all().order_by('?'),
                widget=CheckboxSelectMultiple(),
            )

        self.helper.add_input(Submit('submit', 'Confirmer'))
项目:wger-lycan-clan    作者:andela    | 项目源码 | 文件源码
def get_form_class(self):
        '''
        The form can only show the workouts belonging to the user.

        This is defined here because only at this point during the request
        have we access to the current user
        '''

        class StepForm(ModelForm):
            workout = ModelChoiceField(queryset=Workout.objects.filter(user=self.request.user))

            class Meta:
                model = ScheduleStep
                exclude = ('order', 'schedule')

        return StepForm
项目:wger-lycan-clan    作者:andela    | 项目源码 | 文件源码
def get_form_class(self):
        '''
        The form can only show the workouts belonging to the user.

        This is defined here because only at this point during the request
        have we access to the current user
        '''

        class StepForm(ModelForm):
            workout = ModelChoiceField(queryset=Workout.objects.filter(user=self.request.user))

            class Meta:
                model = ScheduleStep
                exclude = ('order', 'schedule')

        return StepForm
项目:registrasion    作者:chrisjrn    | 项目源码 | 文件源码
def staff_products_form_factory(user):
    ''' Creates a StaffProductsForm that restricts the available products to
    those that are available to a user. '''

    products = inventory.Product.objects.all()
    products = ProductController.available_products(user, products=products)

    product_ids = [product.id for product in products]
    product_set = inventory.Product.objects.filter(id__in=product_ids)

    class StaffProductsForm(forms.Form):
        ''' Form for allowing staff to add an item to a user's cart. '''

        product = forms.ModelChoiceField(
            widget=forms.Select,
            queryset=product_set,
        )

        quantity = forms.IntegerField(
            min_value=0,
        )

    return StaffProductsForm
项目:pyconjp-website    作者:pyconjp    | 项目源码 | 文件源码
def build_presentation_field(self):
        kwargs = {}
        queryset = Presentation.objects.all()
        queryset = queryset.exclude(cancelled=True)
        queryset = queryset.order_by("proposal_base__pk")
        if self.slot.content:
            queryset = queryset.filter(Q(slot=None) | Q(pk=self.slot.content.pk))
            kwargs["required"] = False
            kwargs["initial"] = self.slot.content
        else:
            queryset = queryset.filter(slot=None)
            kwargs["required"] = True
        kwargs["queryset"] = queryset
        return forms.ModelChoiceField(**kwargs)
项目:csv_generator    作者:fatboystring    | 项目源码 | 文件源码
def test_generator_field(self):
        """
        The form should define a generator field
        """
        field = self.form.fields['generator']
        self.assertIsInstance(field, forms.ModelChoiceField)
        self.assertTrue(field.required)
项目:feincms3    作者:matthiask    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self.instance = kwargs.pop('obj')
        self.model = self.instance.__class__

        super(MoveForm, self).__init__(*args, **kwargs)

        self.fields['of'] = forms.ModelChoiceField(
            label=pgettext('MoveForm', 'Of'),
            required=False,
            queryset=self.model.objects.exclude(
                pk__in=self.instance.descendants(),
            ),
            widget=forms.Select(attrs={'size': 30, 'style': 'height:auto'}),
        )

        self.fields['of'].choices = [
            (None, '----------'),
        ] + [
            (
                obj.pk,
                '%s%s' % (
                    (obj.depth - 1) * (
                        '*** ' if obj == self.instance else '--- '),
                    obj,
                ),
            ) for obj in self.fields['of'].queryset
        ]
项目:dal_admin_filters    作者:shamanu4    | 项目源码 | 文件源码
def __init__(self, request, params, model, model_admin):
        if self.parameter_name:
            raise AttributeError(
                'Rename attribute `parameter_name` to '
                '`field_name` for {}'.format(self.__class__)
            )
        self.parameter_name = '{}__id__exact'.format(self.field_name)
        super(AutocompleteFilter, self).__init__(request, params, model, model_admin)

        self._add_media(model_admin)

        field = forms.ModelChoiceField(
            queryset=getattr(model, self.field_name).get_queryset(),
            widget=autocomplete.ModelSelect2(
                url=self.autocomplete_url,
            )
        )

        attrs = self.widget_attrs.copy()
        attrs['id'] = 'id-%s-dal-filter' % self.field_name
        if self.is_placeholder_title:
            attrs['data-placeholder'] = "By " + self.title
        self.rendered_widget = field.widget.render(
            name=self.parameter_name,
            value=self.used_parameters.get(self.parameter_name, ''),
            attrs=attrs
        )
项目:habilitacion    作者:GabrielBD    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(NIForm, self).__init__(*args, **kwargs)
        self.fields['enviar_a'] = forms.ModelChoiceField(queryset=Perfil.objects.all())
项目:django-jsonattrs    作者:Cadasta    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(DepartmentForm, self).__init__(*args, **kwargs)
        self.fields['division'] = ModelChoiceField(
            queryset=Division.objects.all(), empty_label=None
        )
项目:django-jsonattrs    作者:Cadasta    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(ContractForm, self).__init__(*args, **kwargs)
        self.fields['department'] = ModelChoiceField(
            queryset=Department.objects.all(), empty_label=None
        )
项目:silica    作者:zagaran    | 项目源码 | 文件源码
def angular_input_field(form_field, angular_model_name, extra_params={}):

    try:
        form_field_value = form_field.value
        form_field.value = lambda: None
        attrs = {"ng-model": "%s.fields.%s" % (angular_model_name, form_field.name),
                 "class": "form-control"}
        if form_field.field.required:
            attrs["required"] = "true"
        if isinstance(form_field.field, DateTimeField):
            separator = extra_params.pop("silica_datetime_separator", "")
            widget1 = _get_datepicker(form_field, attrs, extra_params)
            attrs["type"] = "time"
            attrs.update(extra_params)
            widget2 = form_field.as_widget(attrs=attrs)
            return format_html(widget1 + separator + widget2)
        if isinstance(form_field.field, DateField):
            return format_html(_get_datepicker(form_field, attrs, extra_params))
        if isinstance(form_field.field, ModelChoiceField):
            pass
            #return format_html(_get_datepicker(form_field, attrs, extra_params))
        if isinstance(form_field.field, ModelMultipleChoiceField):
            pass
            #return format_html(_get_datepicker(form_field, attrs, extra_params))
        attrs.update(extra_params)
        return format_html(form_field.as_widget(attrs=attrs))
    finally:
        form_field.value = form_field_value
项目:stormtrooper    作者:CompileInc    | 项目源码 | 文件源码
def __init__(self, task, *args, **kwargs):
        super(ChoiceAnswerForm, self).__init__(*args, **kwargs)
        if task:
            qs = task.choices
            widget = forms.RadioSelect
            empty_label = None
            count = task.no_of_choices
            if count > settings.TASK_CHOICE_SELECT_CUTOFF:
                widget = forms.Select
                empty_label = BLANK_CHOICE_DASH[0][1]
            self.fields['answer'] = forms.ModelChoiceField(queryset=qs,
                                                           widget=widget,
                                                           empty_label=empty_label)
项目:WorldsAtWar    作者:heidi666    | 项目源码 | 文件源码
def __init__(self, world, *args, **kwargs):
        super(Shiptradeform, self).__init__(*args, **kwargs)
        fleets = fleet.objects.filter(Q(sector=world.sector)|Q(sector='hangar'), world=world, controller=world)
        choices = []
        for tier in v.shipindices:
            for f in fleets:
                if f.__dict__[tier] > 0:
                    choices.append((tier, tier.replace('_', ' ').capitalize()))
                    break
        exclusionlist = []
        for f in fleets:
            if f.power() == 0:
                exclusionlist.append(f.pk)
        for f in exclusionlist:
            fleets = fleets.exclude(pk=f)
        choices = tuple(choices)
        self.fields['offer'] = forms.ChoiceField(choices=choices, label="Ship type")
        self.fields['fleet'] = forms.ModelChoiceField(queryset=fleets, label="From")
        self.fields['offer_amount'] = forms.IntegerField(min_value=1, label="Amount", widget=forms.NumberInput(
                attrs={'size':'10'}))
        self.fields['request'] = forms.ChoiceField(choices=RESOURCE_CHOICES)
        self.fields['request_amount'] = forms.IntegerField(min_value=1, widget=forms.NumberInput(
                attrs={'size':'10'}))
        self.fields['amount'] = forms.IntegerField(min_value=1, widget=forms.NumberInput(
                attrs={'size':'10'}))
    #request = forms.ChoiceField(choices=RESOURCE_CHOICES)
    #request_amount = forms.IntegerField(min_value=1)
    #amount = forms.IntegerField(min_value=1)
项目:WorldsAtWar    作者:heidi666    | 项目源码 | 文件源码
def __init__(self, world, *args, **kwargs):
        super(aidfleetform, self).__init__(*args, **kwargs)
        query = world.controlled_fleets.all().exclude(sector='warping').exclude(sector='hangar')
        self.fields['fleetchoice'] = forms.ModelChoiceField(queryset=query)
        self.fields['retain_control'] = forms.BooleanField(label="Retain ownership")
项目:WorldsAtWar    作者:heidi666    | 项目源码 | 文件源码
def __init__(self, fleets, *args, **kwargs):
        super(PersonalShipForm, self).__init__(*args, **kwargs)
        self.fields['fleetchoice'] = forms.ModelChoiceField(queryset=fleets)
项目:WorldsAtWar    作者:heidi666    | 项目源码 | 文件源码
def __init__(self, pk, *args, **kwargs):
        super(trainfleetform, self).__init__(*args, **kwargs)
        query = fleet.objects.filter(world=pk).exclude(sector='hangar')
        query = query.exclude(sector='warping')
        self.fields['fleet'] = forms.ModelChoiceField(queryset=query, 
            label="Fleet to train", widget=forms.Select(attrs={'id': 'trainchoice', 'onchange': 'trainfleetcost()'}))
项目:WorldsAtWar    作者:heidi666    | 项目源码 | 文件源码
def __init__(self, world, fleetobj, *args, **kwargs):
        super(mergeform, self).__init__(*args, **kwargs)
        if fleetobj.sector == 'hangar':
            fleets = world.fleets.all().filter(sector=world.sector, controller=world)
        elif fleetobj.sector == world.sector:
            fleets = world.fleets.all().filter(Q(sector=world.sector)|Q(sector='hangar'), 
                controller=world).exclude(pk=fleetobj.pk)
        elif fleetobj.sector == 'warping':
            fleets = world.fleets.all().exclude(pk__gte=0) #invalid so niggas who try get no results
        else:
            fleets = world.fleets.all().filter(sector=fleetobj.sector, controller=world).exclude(pk=fleetobj.pk)

        self.fields['fleetchoice'] = forms.ModelChoiceField(queryset=fleets, widget=forms.Select(attrs={'style':'max-width: 105px'}))
项目:Dota2-EU-Ladder    作者:UncleVasya    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(BalancerForm, self).__init__(*args, **kwargs)

        for i in xrange(1, 11):
            self.fields['player_%s' % i] = forms.ModelChoiceField(
                queryset=Player.objects.all(),
                widget=autocomplete.ModelSelect2(url='ladder:player-autocomplete')
            )
项目:django-danceschool    作者:django-danceschool    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(RefundForm, self).__init__(*args, **kwargs)

        this_invoice = kwargs.pop('instance',None)

        for item in this_invoice.invoiceitem_set.all():
            initial = False
            if item.finalEventRegistration:
                initial = item.finalEventRegistration.cancelled
            item_max = item.total + item.taxes if this_invoice.buyerPaysSalesTax else item.total

            self.fields["item_cancelled_%s" % item.id] = forms.BooleanField(
                label=_('Cancelled'),required=False,initial=initial)
            self.fields['item_refundamount_%s' % item.id] = forms.FloatField(
                label=_('Refund Amount'),required=False,initial=(-1) * item.adjustments, min_value=0, max_value=item_max)

        self.fields['comments'] = forms.CharField(
            label=_('Explanation/Comments (optional)'),required=False,
            help_text=_('This information will be added to the comments on the invoice associated with this refund.'),
            widget=forms.Textarea(attrs={'placeholder': _('Enter explanation/comments...'), 'class': 'form-control'}))

        self.fields['id'] = forms.ModelChoiceField(
            required=True,queryset=Invoice.objects.filter(id=this_invoice.id),widget=forms.HiddenInput(),initial=this_invoice.id)

        self.fields['initial_refund_amount'] = forms.FloatField(
            required=True,initial=(-1) * this_invoice.adjustments,min_value=0,max_value=this_invoice.amountPaid + this_invoice.refunds,widget=forms.HiddenInput())

        self.fields['total_refund_amount'] = forms.FloatField(
            required=True,initial=0,min_value=0,max_value=this_invoice.amountPaid + this_invoice.refunds,widget=forms.HiddenInput())
项目:django-danceschool    作者:django-danceschool    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)

        # Ensure 'initial' is initialized to avoid KeyError issues and fill in the Sub category
        kwargs['initial'] = kwargs.get('initial',{})
        kwargs['initial'].update({'category': getConstant('general__eventStaffCategorySubstitute').id})

        # If the user is a staffMember, then populate the form with their info
        if hasattr(user,'staffmember'):
            kwargs['initial'].update({
                'staffMember': user.staffmember,
                'submissionUser': user,
            })

        super(SubstituteReportingForm,self).__init__(*args,**kwargs)
        self.fields['event'] = forms.ModelChoiceField(queryset=Series.objects.order_by('-startTime'))
        self.fields['staffMember'] = forms.ModelChoiceField(queryset=Instructor.objects.exclude(
            status__in=[
                Instructor.InstructorStatus.hidden,
                Instructor.InstructorStatus.retired,
                Instructor.InstructorStatus.retiredGuest
            ]).order_by('status','lastName','firstName'))
        self.fields['replacedStaffMember'] = SeriesTeacherChoiceField(queryset=SeriesTeacher.objects.none())
        self.fields['occurrences'] = SeriesClassesChoiceField(queryset=EventOccurrence.objects.none())
        self.fields['submissionUser'].widget = forms.HiddenInput()
        self.fields['category'].widget = forms.HiddenInput()
项目:django-danceschool    作者:django-danceschool    | 项目源码 | 文件源码
def add_fields(self, form, index):
        super(EventOccurrenceCustomFormSet,self).add_fields(form,index)
        form.fields['startTime'] = forms.SplitDateTimeField(label=_("Start Time"),input_time_formats=['%I:%M%p','%-I:%M%p'], widget=widgets.SplitDateTimeWidget)
        form.fields['endTime'] = forms.SplitDateTimeField(label=_("End Time"),input_time_formats=['%I:%M%p','%-I:%M%p'], widget=widgets.SplitDateTimeWidget)
        form.fields['extraOccurrencesToAdd'] = forms.IntegerField(label=_("Repeat __ times:"),initial=0,min_value=0,max_value=100,required=False)
        form.fields['extraOccurrenceRule'] = forms.ChoiceField(label=_("Every:"),choices=EVENT_REPEAT_CHOICES,required=False)
        form.fields['sendReminderTo'] = forms.ChoiceField(label=_("Send A Reminder To:"),choices=REMINDER_SET_CHOICES,initial='none',required=False)
        form.fields['sendReminderWhen'] = forms.ChoiceField(label=_("Before:"),choices=REMINDER_TIME_CHOICES,initial=0,required=False)
        form.fields['sendReminderWhich'] = forms.ChoiceField(label=_("Ahead Of:"),choices=(('all',_('All Occurrences')),('first',_('First Occurrence Only'))),initial='all',required=False)
        form.fields['sendReminderGroup'] = forms.ModelChoiceField(label=_("Remind Group:"),queryset=Group.objects.all(),required=False)
        form.fields['sendReminderUsers'] = forms.ModelMultipleChoiceField(label=_("Remind Users:"),queryset=User.objects.filter(staffmember__isnull=False),required=False)
项目:graphene-django    作者:graphql-python    | 项目源码 | 文件源码
def test_should_manytoone_convert_connectionorlist():
    field = forms.ModelChoiceField(Reporter.objects.all())
    graphene_type = convert_form_field(field)
    assert isinstance(graphene_type, graphene.ID)
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def formfield(self, **kwargs):
        db = kwargs.pop('using', None)
        if isinstance(self.remote_field.model, six.string_types):
            raise ValueError("Cannot create form field for %r yet, because "
                             "its related model %r has not been loaded yet" %
                             (self.name, self.remote_field.model))
        defaults = {
            'form_class': forms.ModelChoiceField,
            'queryset': self.remote_field.model._default_manager.using(db),
            'to_field_name': self.remote_field.field_name,
        }
        defaults.update(kwargs)
        return super(ForeignKey, self).formfield(**defaults)
项目:metronus    作者:Metronus    | 项目源码 | 文件源码
def __init__(self, user, *args, **kwargs):
        super(ProjectDepartmentForm, self).__init__(*args, **kwargs)
        self.fields['project_id'] = forms.ModelChoiceField(queryset=Project.objects.filter(
            company_id=user.company_id, deleted=False))
        self.fields['department_id'] = forms.ModelChoiceField(queryset=Department.objects.filter(
            company_id=user.company_id, active=True))
项目:workshops.qiime2.org    作者:qiime2    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        workshop = kwargs.pop('workshop')
        super().__init__(*args, **kwargs)
        qs = PosterOption.objects.filter(workshop__slug=workshop)
        if qs.count() != 0:
            self.fields['poster_option'] = forms.ModelChoiceField(
                queryset=qs)
项目:sadm    作者:prologin    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(MatchCreationForm, self).__init__(*args, **kwargs)
        self.helper = BaseFormHelper()
        self.champions = []
        champions = (models.Champion.objects
                           .filter(deleted=False, status='ready')
                           .select_related('author'))
        if (settings.STECHEC_FIGHT_ONLY_OWN_CHAMPIONS and not
            self.request.user.is_staff):
            champions = champions.filter(author=self.request.user)
        for i in range(1, settings.STECHEC_NPLAYERS + 1):
            f = forms.ModelChoiceField(label="Champion %d" % i,
                                       queryset=champions,
                                       widget=forms.Select(attrs={'class': 'select2'}))
            self.fields['champion_%d' % i] = f
            self.helper.append_field('champion_%d' % i)
            self.champions.append(f)

        if settings.STECHEC_USE_MAPS:
            self.fields['map'] = forms.ChoiceField(required=True,
                                                   widget=MapSelect(attrs={'class': 'mapselect select2'}),
                                                   label="Carte utilisée")

            all_maps = models.Map.objects.select_related('author').order_by('author__username', 'name')
            self.fields['map'].choices = [
                ('Officielles', [(map.id, map) for map in all_maps if map.official])
            ] + [
                (author, [(map.id, map) for map in maps])
                for author, maps in groupby(
                    (map for map in all_maps if not map.official),
                    lambda map: map.author
                )
            ]
            self.helper.append_field('map')

        self.helper.append_submit("Lancer le match")
项目:Odin    作者:HackSoftware    | 项目源码 | 文件源码
def __init__(self, course, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['week'] = forms.ModelChoiceField(
            queryset=Week.objects.filter(course=course).order_by('number')
        )
项目:Odin    作者:HackSoftware    | 项目源码 | 文件源码
def __init__(self, course, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['topic'] = forms.ModelChoiceField(
            queryset=Topic.objects.filter(course=course)
        )
项目:Odin    作者:HackSoftware    | 项目源码 | 文件源码
def __init__(self, course, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['topic'] = forms.ModelChoiceField(
            queryset=Topic.objects.filter(course=course)
        )
项目:Odin    作者:HackSoftware    | 项目源码 | 文件源码
def __init__(self, course=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if course:
            self.fields['topic'] = forms.ModelChoiceField(
                queryset=Topic.objects.filter(course=course)
            )
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def formfield(self, **kwargs):
        db = kwargs.pop('using', None)
        if isinstance(self.remote_field.model, six.string_types):
            raise ValueError("Cannot create form field for %r yet, because "
                             "its related model %r has not been loaded yet" %
                             (self.name, self.remote_field.model))
        defaults = {
            'form_class': forms.ModelChoiceField,
            'queryset': self.remote_field.model._default_manager.using(db),
            'to_field_name': self.remote_field.field_name,
        }
        defaults.update(kwargs)
        return super(ForeignKey, self).formfield(**defaults)
项目:the-contract-site    作者:shadytradesman    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self.game = kwargs.pop('game')
        super(ValidateAttendanceForm, self).__init__(*args, **kwargs)
        self.fields['player'] = forms.ModelChoiceField(queryset=self.game.invitations.all(),
                                        required=False)
        self.fields['character'] = forms.ModelChoiceField(Character.objects.filter(player__in=self.game.invitations.filter()),
                                           empty_label="NPC Ringer",
                                           required=False)
        self.fields['character'].widget.attrs['hidden'] = True
        self.fields['player'].widget.attrs['hidden'] = True
项目:the-contract-site    作者:shadytradesman    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        # self.initial is set in super
        super(DeclareOutcomeForm, self).__init__(*args, **kwargs)
        attendance = self.initial['game_attendance']
        if attendance.attending_character:
            self.fields['outcome'] = forms.ChoiceField(choices=OUTCOME[:4])
        else:
            self.fields['outcome'] = forms.ChoiceField(choices=OUTCOME[4:6])
        self.fields['hidden_attendance'] = forms.ModelChoiceField(self.initial['game_attendance'].relevant_game.game_attendance_set.all(),
                                                   required=False)
        self.fields['hidden_attendance'].widget.attrs['hidden'] = True
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def formfield(self, **kwargs):
        db = kwargs.pop('using', None)
        if isinstance(self.remote_field.model, six.string_types):
            raise ValueError("Cannot create form field for %r yet, because "
                             "its related model %r has not been loaded yet" %
                             (self.name, self.remote_field.model))
        defaults = {
            'form_class': forms.ModelChoiceField,
            'queryset': self.remote_field.model._default_manager.using(db),
            'to_field_name': self.remote_field.field_name,
        }
        defaults.update(kwargs)
        return super(ForeignKey, self).formfield(**defaults)
项目:a4-meinberlin    作者:liqd    | 项目源码 | 文件源码
def field(self):
        return forms.ModelChoiceField(
            queryset=self.target_model.objects.filter(
                is_draft=False,
                is_archived=False,
                is_public=True),
            widget=self.widget,
            required=self._required,
            help_text=self._help_text)
项目:longclaw    作者:JamesRamm    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        site = kwargs.pop('site', None)
        super(AddressForm, self).__init__(*args, **kwargs)

        # Edit the country field to only contain
        # countries specified for shipping
        all_countries = True
        if site:
            settings = LongclawSettings.for_site(site)
            all_countries = settings.default_shipping_enabled
        if all_countries:
            queryset = Country.objects.all()
        else:
            queryset = Country.objects.exclude(shippingrate=None)
        self.fields['country'] = ModelChoiceField(queryset)
项目:edd    作者:JBEI    | 项目源码 | 文件源码
def get_merge_form(self, request):
        class MergeForm(forms.Form):
            # same name as admin site uses for checkboxes to select items for actions
            _selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
            mtype = forms.ModelChoiceField(
                self.get_queryset(request),
                label=self.model._meta.verbose_name,
                widget=self.get_merge_autowidget(),
            )
        return MergeForm
项目:djongo    作者:nesdis    | 项目源码 | 文件源码
def __init__(self, name, model_form_class, model_form_kw, *args, **kwargs):
        form_fields = []
        mdl_form_field_names = []
        widgets = []
        model_form_kwargs = model_form_kw.copy()

        try:
            model_form_kwargs['prefix'] = model_form_kwargs['prefix'] + '-' + name
        except KeyError:
            model_form_kwargs['prefix'] = name

        initial = kwargs.pop('initial', None)
        if initial:
            model_form_kwargs['initial'] = initial

        self.model_form_class = model_form_class
        self.model_form_kwargs = model_form_kwargs

        error_messages = {
            'incomplete': 'Enter all required fields.',
        }

        self.model_form = model_form_class(**model_form_kwargs)
        for field_name, field in self.model_form.fields.items():
            if isinstance(field, (forms.ModelChoiceField, forms.ModelMultipleChoiceField)):
                continue
            form_fields.append(field)
            mdl_form_field_names.append(field_name)
            widgets.append(field.widget)

        widget = EmbeddedFormWidget(mdl_form_field_names, widgets)
        super().__init__(error_messages=error_messages, fields=form_fields,
                         widget=widget, require_all_fields=False, *args, **kwargs)
项目:wger-lycan-clan    作者:andela    | 项目源码 | 文件源码
def get_form_class(self):
        '''
        The form can only show units in the user's language
        '''

        class IngredientWeightUnitForm(ModelForm):
            unit = ModelChoiceField(queryset=WeightUnit.objects.filter(language=load_language()))

            class Meta:
                model = IngredientWeightUnit
                fields = ['unit', 'gram', 'amount']

        return IngredientWeightUnitForm
项目:wger-lycan-clan    作者:andela    | 项目源码 | 文件源码
def get_form_class(self):
        '''
        The form can only show units in the user's language
        '''

        class IngredientWeightUnitForm(ModelForm):
            unit = ModelChoiceField(queryset=WeightUnit.objects.filter(language=load_language()))

            class Meta:
                model = IngredientWeightUnit
                fields = ['unit', 'gram', 'amount']

        return IngredientWeightUnitForm
项目:alterchef    作者:libremesh    | 项目源码 | 文件源码
def __init__(self, data=None, *args, **kwargs):
        user = kwargs.pop('user')
        super(FwProfileCommon, self).__init__(data, *args, **kwargs)
        self.fields['network'] = forms.ModelChoiceField(queryset=Network.objects.with_user_perms(user))
        self.fields['based_on'].choices = make_base_on_choices(user)
        self.fields['ssh_keys'] = _create_ssh_keys_field(data, kwargs, user)
        instance = kwargs.get("instance")
        revision_choices = build_revision_choices()
        if revision_choices:
            initial = instance.openwrt_revision if instance else \
                filter(lambda x: "stable" in x[1], revision_choices)[0][0]
            self.fields["openwrt_revision"] = forms.ChoiceField(choices=revision_choices,
                                                                initial=initial)
项目:Kiwi    作者:kiwitcms    | 项目源码 | 文件源码
def to_python(self, value):
        try:
            return super(ModelChoiceField, self).to_python(value)
        except ValidationError as e:
            raise ValidationError(e.messages[0] % {'value': value})