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

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

项目:postix    作者:c3cashdesk    | 项目源码 | 文件源码
def get_form_and_formset(
    request: HttpRequest=None, extra: int=1, initial_form: SessionBaseForm=None,
    initial_formset=None
) -> Tuple[SessionBaseForm, Any]:
    ItemMovementFormSet = forms.formset_factory(ItemMovementForm, extra=extra)

    if request:
        form = SessionBaseForm(request.POST, prefix='session')
        formset = ItemMovementFormSet(request.POST, prefix='items')
    elif initial_form or initial_formset:
        form = SessionBaseForm(initial=initial_form, prefix='session')
        formset = ItemMovementFormSet(initial=initial_formset, prefix='items')
    else:
        form = SessionBaseForm(prefix='session')
        formset = ItemMovementFormSet(prefix='items')
    return form, formset
项目:the-contract-site    作者:shadytradesman    | 项目源码 | 文件源码
def get_create_power_context_from_base(base_power):
    system = Base_Power_System.objects.filter(dice_system=DICE_SYSTEM[1][0]).get(base_power=base_power)
    primary_form = CreatePowerForm(base_power, initial={'system': system.system_text})
    enhancement_forms = []
    for enhancement in Enhancement.objects.filter(pk__in=base_power.enhancements.all()):
        enhancement_forms.append(formset_factory(make_enhancement_form(enhancement), extra = 1)())
    drawback_forms = []
    for drawback in Drawback.objects.filter(pk__in=base_power.drawbacks.all()):
        drawback_forms.append(formset_factory(make_drawback_form(drawback), extra = 1)())
    parameter_forms = []
    for parameter in Power_Param.objects.filter(relevant_base_power=base_power).all():
        parameter_forms.append(formset_factory(make_parameter_form(parameter))())
    system = Base_Power_System.objects.filter(dice_system=DICE_SYSTEM[1][0]).get(base_power=base_power.slug)
    requirements = get_modifier_requirements(Enhancement.objects.filter(pk__in=base_power.enhancements.all()),
                                             Drawback.objects.filter(pk__in=base_power.drawbacks.all()))
    context = {
        'base_power': base_power,
        'power_system': system,
        'form': primary_form,
        'parameters': parameter_forms,
        'enhancements': enhancement_forms,
        'drawbacks': drawback_forms,
        'requirements_json': json.dumps(requirements),
    }
    return context
项目:the-contract-site    作者:shadytradesman    | 项目源码 | 文件源码
def get_enhancement_formsets_from_power(power):
    enhancement_forms = []
    enhancement_instances = Enhancement_Instance.objects.filter(relevant_power=power).all()
    for base_enhancement in Enhancement.objects.filter(pk__in=power.base.enhancements.all()):
        instances_of_this_enhancement = set(
            x for x in enhancement_instances if (x.relevant_enhancement == base_enhancement))
        init = []
        num_extra = 0
        for enhancement_instance in instances_of_this_enhancement:
            init.append({
                'is_selected': True,
                'detail_text': enhancement_instance.detail,
            })
        if base_enhancement.multiplicity_allowed or not instances_of_this_enhancement:
            num_extra = 1
        new_form = formset_factory(make_enhancement_form(base_enhancement), extra=num_extra, max_num=4)(initial=init)
        enhancement_forms.append(new_form)
    return enhancement_forms
项目:the-contract-site    作者:shadytradesman    | 项目源码 | 文件源码
def get_drawback_formsets_from_power(power):
    drawback_forms = []
    drawback_instances = Drawback_Instance.objects.filter(relevant_power=power).all()
    for base_drawback in Drawback.objects.filter(pk__in=power.base.drawbacks.all()):
        instances_of_this_drawback = set(
            x for x in drawback_instances if (x.relevant_drawback == base_drawback))
        init = []
        num_extra = 0
        for drawback_instance in instances_of_this_drawback:
            init.append({
                'is_selected': True,
                'detail_text': drawback_instance.detail,
            })
        if base_drawback.multiplicity_allowed or not instances_of_this_drawback:
            num_extra = 1
        new_form = formset_factory(make_drawback_form(base_drawback), extra=num_extra, max_num=4)(initial=init)
        drawback_forms.append(new_form)
    return drawback_forms
项目:djongo    作者:nesdis    | 项目源码 | 文件源码
def __init__(self, form, field, name):
        super().__init__(form, field, name)
        ArrayFormSet = forms.formset_factory(field.model_form_class, can_delete=True)

        data = self.data if form.is_bound else None
        initial = []
        if self.initial is not None:
            for ini in self.initial:
                if isinstance(ini, Model):
                    initial.append(
                        forms.model_to_dict(
                            ini,
                            fields=field.model_form_class._meta.fields,
                            exclude=field.model_form_class._meta.exclude
                        ))

        self.form_set = ArrayFormSet(data, initial=initial,
                                     prefix=name)
项目:amadeuslms    作者:amadeusproject    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        self.object = None

        form_class = self.get_form_class()
        form = self.get_form(form_class)

        slug = self.kwargs.get('slug', '')
        goals = get_object_or_404(Goals, slug = slug)

        MyGoalsFormset = formset_factory(MyGoalsForm, extra = 0)
        my_goals_formset = MyGoalsFormset(self.request.POST, initial = [{'item': x.id, 'value': x.ref_value} for x in goals.item_goal.all()])

        if (my_goals_formset.is_valid()):
            return self.form_valid(my_goals_formset)
        else:
            return self.form_invalid(my_goals_formset)
项目:Django-Forms-Formsets    作者:codingforentrepreneurs    | 项目源码 | 文件源码
def formset_view(request):
    if request.user.is_authenticated():
        PostModelFormset = modelformset_factory(Post, form=PostModelForm)
        formset = PostModelFormset(request.POST or None, 
                queryset=Post.objects.filter(user=request.user))
        if formset.is_valid():
            #formset.save(commit=False)
            for form in formset:
                print(form.cleaned_data)
                obj = form.save(commit=False)
                if form.cleaned_data:
                    #obj.title = "This title %s" %(obj.id)
                    if not form.cleaned_data.get("publish"):
                        obj.publish = timezone.now()
                    obj.save()
            # return redirect("/")
                #print(form.cleaned_data)
        context = {
            "formset": formset
        }
        return render(request, "formset_view.html", context)
    else:
        raise Http404


# def formset_view(request):
#     TestFormset = formset_factory(TestForm, extra=2)
#     formset = TestFormset(request.POST or None)
#     if formset.is_valid():
#         for form in formset:
#             print(form.cleaned_data)
#     context = {
#         "formset": formset
#     }
#     return render(request, "formset_view.html", context)
项目:lfmsh_bank_2.0    作者:nkorobkov    | 项目源码 | 文件源码
def get_blank_form(cls, creator_username):
        p2p_formset = formset_factory(
            wraps(P2PKernelForm)(partial(P2PKernelForm, creator=User.objects.get(username=creator_username))), max_num=1)
        return p2p_formset
项目:lfmsh_bank_2.0    作者:nkorobkov    | 项目源码 | 文件源码
def get_blank_form(cls, creator_username):
        lab_formset = formset_factory(LabKernelForm, max_num=1)
        return lab_formset
项目:lfmsh_bank_2.0    作者:nkorobkov    | 项目源码 | 文件源码
def get_blank_form(cls, creator_username):
        students_query = __class__._get_student_query()
        return formset_factory(cls._get_kernel_form(), max_num=len(students_query))
项目:the-contract-site    作者:shadytradesman    | 项目源码 | 文件源码
def get_create_power_context_from_power(power):
    primary_form = CreatePowerForm(power.base,
                                   initial={'system': power.system,
                                            'description': power.description,
                                            'flavor': power.flavor_text,
                                            'activation_style': power.activation_style,
                                            'power_name': power.name})
    enhancement_forms = get_enhancement_formsets_from_power(power)
    drawback_forms = get_drawback_formsets_from_power(power)
    parameter_forms = []
    for parameter_value in Parameter_Value.objects.filter(relevant_power=power).all():
        init= [{'level_picker': parameter_value.value}]
        parameter_forms.append(formset_factory(make_parameter_form(parameter_value.relevant_power_param), extra = 0)(initial = init))
    system = Base_Power_System.objects.filter(dice_system=DICE_SYSTEM[1][0]).get(base_power=power.base.slug)
    requirements = get_modifier_requirements(Enhancement.objects.filter(pk__in=power.base.enhancements.all()),
                                             Drawback.objects.filter(pk__in=power.base.drawbacks.all()))
    context = {
        'base_power': power.base,
        'power_system': system,
        'form': primary_form,
        'parameters': parameter_forms,
        'enhancements': enhancement_forms,
        'drawbacks': drawback_forms,
        'requirements_json': json.dumps(requirements),
    }
    return context
项目:djongo    作者:nesdis    | 项目源码 | 文件源码
def __init__(self, name, model_form_class, mdl_form_kw_l, *args, **kwargs):
        self.name = name
        self.model_form_class = model_form_class
        self.mdl_form_kw_l = mdl_form_kw_l

        widget = ArrayFormWidget(model_form_class._meta.fields[0])
        error_messages = {
            'incomplete': 'Enter all required fields.',
        }

        self.ArrayFormSet = forms.formset_factory(self.model_form_class, can_delete=True)
        super().__init__(error_messages=error_messages,
                         widget=widget, *args, **kwargs)
项目:perdiem-django    作者:RevolutionTech    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        view_formset = formset_factory(self.get_form_class(), **self.get_formset_factory_kwargs())

        if self.request.method == 'GET':
            formset = view_formset(initial=self.get_initial())
        elif self.request.method == 'POST':
            formset = view_formset(self.request.POST, initial=self.get_initial())
        else:
            raise Http405

        context = {'formset': formset}
        return context
项目:amadeuslms    作者:amadeusproject    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        context = super(ReportView, self).get_context_data(**kwargs)
        subject = Subject.objects.get(id=self.request.GET['subject_id'])

        context['title'] = _('Interaction Data')
        context['subject'] = subject   

        #set formset
        resourceTagFormSet = formset_factory(ResourceAndTagForm, formset=BaseResourceAndTagFormset)
        resourceTagFormSet = resourceTagFormSet()
        context['resource_tag_formset'] = resourceTagFormSet
        return context
项目:amadeuslms    作者:amadeusproject    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        """
        Handles POST requests, instantiating a form instance with the passed
        POST variables and then checked for validity.
        """
        form = self.get_form()

        subject = Subject.objects.get(id=self.request.GET['subject_id'])

        topics = subject.topic_subject.all()
        #get all resources associated with topics
        tags = []
        for topic in topics:
            resources_set = topic.resource_topic.all()
            for resource in resources_set:
                for tag in resource.tags.all():
                    tags.append(tag)


        t = Tag(name=" ")
        t.id = -1 #so I know he choose empyt one
        tags.append(t)
        classes = Resource.__subclasses__()  
        amount_of_forms = self.request.POST['form-TOTAL_FORMS']
        initial_datum = {'class_name': classes , 'tag': tags}
        initial_data = []
        for i in range(int(amount_of_forms)):
            initial_data.append(initial_datum)

        resourceTagFormSet = formset_factory(ResourceAndTagForm, formset=BaseResourceAndTagFormset)
        resources_formset = resourceTagFormSet(self.request.POST, initial = initial_data)
        if form.is_valid() and resources_formset.is_valid():
            self.form_data = form.cleaned_data
            self.formset_data = resources_formset.cleaned_data
            return self.form_valid(form)
        else:
            return self.form_invalid(form)
项目:amadeuslms    作者:amadeusproject    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        self.object = None

        form_class = self.get_form_class()
        form = self.get_form(form_class)

        slug = self.kwargs.get('slug', '')
        goals = get_object_or_404(Goals, slug = slug)

        MyGoalsFormset = formset_factory(MyGoalsForm, extra = 0)
        my_goals_formset = MyGoalsFormset(initial = [{'item': x.id, 'value': x.ref_value} for x in goals.item_goal.all()])

        self.log_action = "view"

        self.log_context['category_id'] = goals.topic.subject.category.id
        self.log_context['category_name'] = goals.topic.subject.category.name
        self.log_context['category_slug'] = goals.topic.subject.category.slug
        self.log_context['subject_id'] = goals.topic.subject.id
        self.log_context['subject_name'] = goals.topic.subject.name
        self.log_context['subject_slug'] = goals.topic.subject.slug
        self.log_context['topic_id'] = goals.topic.id
        self.log_context['topic_name'] = goals.topic.name
        self.log_context['topic_slug'] = goals.topic.slug
        self.log_context['goals_id'] = goals.id
        self.log_context['goals_name'] = goals.name
        self.log_context['goals_slug'] = goals.slug
        self.log_context['timestamp_start'] = str(int(time.time()))

        super(NewWindowSubmit, self).createLog(self.request.user, self.log_component, self.log_action, self.log_resource, self.log_context) 

        self.request.session['log_id'] = Log.objects.latest('id').id

        self.log_context = {}

        return self.render_to_response(self.get_context_data(my_goals_formset = my_goals_formset))
项目:amadeuslms    作者:amadeusproject    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        self.object = None

        form_class = self.get_form_class()
        form = self.get_form(form_class)

        slug = self.kwargs.get('slug', '')
        goals = get_object_or_404(Goals, slug = slug)

        MyGoalsFormset = formset_factory(MyGoalsForm, extra = 0)
        my_goals_formset = MyGoalsFormset(initial = [{'item': x.id, 'value': x.ref_value} for x in goals.item_goal.all()])

        self.log_action = "view"

        self.log_context['category_id'] = goals.topic.subject.category.id
        self.log_context['category_name'] = goals.topic.subject.category.name
        self.log_context['category_slug'] = goals.topic.subject.category.slug
        self.log_context['subject_id'] = goals.topic.subject.id
        self.log_context['subject_name'] = goals.topic.subject.name
        self.log_context['subject_slug'] = goals.topic.subject.slug
        self.log_context['topic_id'] = goals.topic.id
        self.log_context['topic_name'] = goals.topic.name
        self.log_context['topic_slug'] = goals.topic.slug
        self.log_context['goals_id'] = goals.id
        self.log_context['goals_name'] = goals.name
        self.log_context['goals_slug'] = goals.slug
        self.log_context['timestamp_start'] = str(int(time.time()))

        super(SubmitView, self).createLog(self.request.user, self.log_component, self.log_action, self.log_resource, self.log_context) 

        self.request.session['log_id'] = Log.objects.latest('id').id

        self.log_context = {}

        return self.render_to_response(self.get_context_data(my_goals_formset = my_goals_formset))
项目:iguana    作者:iguana-project    | 项目源码 | 文件源码
def get(self, request):
        formset = formset_factory(EmailFormField, extra=0, max_num=self.max_number_of_invitables,
                                  min_num=1, validate_max=True, formset=EmailFormSet)
        cp = request.GET.copy()
        # TODO how can i provide the platform via function to the template?
        #      somehow i couldn't call the desired function from template
        return render(request, 'invite_users/invite_users.html', {'form': self.form_class(), 'formset': formset,
                                                                  'platform': settings.PLATFORM})
项目:registrasion    作者:chrisjrn    | 项目源码 | 文件源码
def ProductsForm(category, products):
    ''' Produces an appropriate _ProductsForm subclass for the given render
    type. '''

    # Each Category.RENDER_TYPE value has a subclass here.
    cat = inventory.Category
    RENDER_TYPES = {
        cat.RENDER_TYPE_QUANTITY: _QuantityBoxProductsForm,
        cat.RENDER_TYPE_RADIO: _RadioButtonProductsForm,
        cat.RENDER_TYPE_ITEM_QUANTITY: _ItemQuantityProductsForm,
        cat.RENDER_TYPE_CHECKBOX: _CheckboxProductsForm,
    }

    # Produce a subclass of _ProductsForm which we can alter the base_fields on
    class ProductsForm(RENDER_TYPES[category.render_type]):
        pass

    products = list(products)
    products.sort(key=lambda prod: prod.order)

    ProductsForm.set_fields(category, products)

    if category.render_type == inventory.Category.RENDER_TYPE_ITEM_QUANTITY:
        ProductsForm = forms.formset_factory(
            ProductsForm,
            formset=_ItemQuantityProductsFormSet,
        )

    return ProductsForm
项目:registrasion    作者:chrisjrn    | 项目源码 | 文件源码
def staff_products_formset_factory(user):
    ''' Creates a formset of StaffProductsForm for the given user. '''
    form_type = staff_products_form_factory(user)
    return forms.formset_factory(form_type)
项目:django-dynamic-fields    作者:yourlabs    | 项目源码 | 文件源码
def get_form_class(self):
        return formset_factory(
            super(FormSetView, self).get_form_class(),
            extra=2
        )
项目:the-contract-site    作者:shadytradesman    | 项目源码 | 文件源码
def end_game(request, game_id):
    game = get_object_or_404(Game, id=game_id)
    if not request.user.has_perm('edit_game', game):
        return HttpResponseForbidden()
    if not game.is_active:
        return HttpResponseForbidden()
    DeclareOutcomeFormset = formset_factory(DeclareOutcomeForm, extra=0)
    game_attendances = game.game_attendance_set.all()
    initial_data = []
    for game_attendance in game_attendances:
        initial = {
            'player': game_attendance.game_invite.invited_player.id,
            'game_attendance': game_attendance,
            'hidden_attendance': game_attendance.id,
        }
        initial_data.append(initial)
    if request.method == 'POST':
        declare_outcome_formset = DeclareOutcomeFormset(request.POST,
                                            initial=initial_data)
        game_feedback_form = GameFeedbackForm(request.POST)
        if declare_outcome_formset.is_valid() and game_feedback_form.is_valid():
            for form in declare_outcome_formset:
                attendance = get_object_or_404(Game_Attendance, id=form.cleaned_data['hidden_attendance'].id)
                attendance.outcome = form.cleaned_data['outcome']
                if form.cleaned_data['notes']:
                    attendance.notes = form.cleaned_data['notes']
                attendance.save()
            if game_feedback_form.cleaned_data['scenario_notes']:
                game.scenario_notes = game_feedback_form.cleaned_data['scenario_notes']
            game.save()
            game.transition_to_finished()
            return HttpResponseRedirect(reverse('games:games_view_game', args=(game.id,)))
        else:
            print(declare_outcome_formset.errors + game_feedback_form.errors)
            return None
    else:
        formset = DeclareOutcomeFormset(initial=initial_data)
        game_feedback = GameFeedbackForm()
        context = {
            'formset':formset,
            'feedback_form':game_feedback,
            'game':game,
        }
        return render(request, 'games/end_game.html', context)