我们从Python开源项目中,提取了以下34个代码示例,用于说明如何使用django.forms.models.inlineformset_factory()。
def get_formset(request, exercise_pk, reps=Set.DEFAULT_SETS): ''' Returns a formset. This is then rendered inside the new set template ''' exercise = Exercise.objects.get(pk=exercise_pk) SettingFormSet = inlineformset_factory(Set, Setting, can_delete=False, extra=int(reps), fields=SETTING_FORMSET_FIELDS) formset = SettingFormSet(queryset=Setting.objects.none(), prefix='exercise{0}'.format(exercise_pk)) return render(request, "set/formset.html", {'formset': formset, 'exercise': exercise})
def CrearCobro(request,empleado_slug=None,cliente_slug=None): cliente = Cliente.objects.get(slug=cliente_slug) cobro_form = CobroForm(request.POST or None) ServicioFormSet = inlineformset_factory(Cobro,Servicio, form=ServicioForm,formset=RequiredBaseInlineFormSet, max_num=10, extra=1) servicio_formset = ServicioFormSet(request.POST or None, prefix='servicio') if cobro_form.is_valid() and servicio_formset.is_valid(): cobro = cobro_form.save() servicio = servicio_formset.save(commit=False) for serv in servicio: serv.cobro = cobro serv.save() messages.add_message(request, messages.INFO, 'El cobro se ha registrado correctamente') return HttpResponseRedirect(cobro.get_absolute_url()) return render_to_response( 'cobranzas/nuevo_cobro.html', { 'form': cobro_form, 'formset': servicio_formset, 'cliente': cliente, }, context_instance = RequestContext(request) )
def EditarCobro(request,empleado_slug=None,cliente_slug=None,cobro_slug=None): if not request.user.is_staff or not request.user.is_superuser: raise Http404 cliente = Cliente.objects.get(slug=cliente_slug) instance = Cobro.objects.get(slug=cobro_slug) cobro_form = CobroForm(request.POST or None,instance=instance) ServicioFormSet = inlineformset_factory(Cobro,Servicio, form=ServicioForm,formset=RequiredBaseInlineFormSet, max_num=10, extra=1) servicio_formset = ServicioFormSet(request.POST or None, prefix='servicio', instance=instance) if cobro_form.is_valid() and servicio_formset.is_valid(): cobro = cobro_form.save() servicio = servicio_formset.save(commit=False) for serv in servicio: serv.cobro = cobro serv.save() messages.add_message(request, messages.INFO, 'El cobro se ha editado correctamente') return HttpResponseRedirect(cobro.get_absolute_url()) return render_to_response( 'cobranzas/nuevo_cobro.html', { 'form': cobro_form, 'formset': servicio_formset, 'cliente': cliente, }, context_instance = RequestContext(request) )
def CreateLibros(request,empleado_slug=None,cliente_slug=None): uit_form = UITForm(request.POST or None) TipoLibroFormSet = inlineformset_factory(UIT, TipoLibro, form=TipoLibroForm,formset=RequiredBaseInlineFormSet, max_num=12, extra=1) tipolibro_formset = TipoLibroFormSet(request.POST or None, prefix='tipolibro') if uit_form.is_valid() and tipolibro_formset.is_valid(): uit = uit_form.save() tipolibro = tipolibro_formset.save(commit=False) for lib in tipolibro: lib.uit = uit lib.save() messages.add_message(request, messages.INFO, 'Se ha registrado correctamente') return HttpResponseRedirect(uit.get_absolute_url()) return render_to_response( 'libros/libro_form.html', { 'form': uit_form, 'formset':tipolibro_formset, }, context_instance = RequestContext(request) )
def UpdateLibros(request,empleado_slug=None,cliente_slug=None,uit_pk=None): if not request.user.is_staff or not request.user.is_superuser: raise Http404 instance = UIT.objects.get(pk=uit_pk) uit_form = UITForm(request.POST or None, instance=instance) TipoLibroFormSet = inlineformset_factory(UIT, TipoLibro, form=TipoLibroForm,formset=RequiredBaseInlineFormSet, max_num=12, extra=1) tipolibro_formset = TipoLibroFormSet(request.POST or None, prefix='tipolibro', instance=instance) if uit_form.is_valid() and tipolibro_formset.is_valid(): uit = uit_form.save() tipolibro = tipolibro_formset.save(commit=False) for lib in tipolibro: lib.uit = uit lib.save() messages.add_message(request, messages.INFO, 'Se ha editado correctamente') return HttpResponseRedirect(uit.get_absolute_url()) return render_to_response( 'libros/libro_form.html', { 'form': uit_form, 'formset':tipolibro_formset, }, context_instance = RequestContext(request) )
def nested_formset_factory(parent_model, child_model, grandchild_model): parent_child = inlineformset_factory( parent_model, child_model, formset=BaseNestedFormset, max_num=1, fields="__all__", widgets={'type': forms.RadioSelect(), 'text': forms.Textarea({'class': 'materialize-textarea'}) }, extra=1, exclude=['help_text', 'order', ], can_order=True, can_delete=True, ) parent_child.nested_formset_class = inlineformset_factory( child_model, grandchild_model, max_num=8, extra=4, validate_max=True, widgets={'text': forms.TextInput()}, exclude=['ORDER', ], can_delete=True, ) return parent_child # The best link: http://yergler.net/blog/2009/09/27/nested-formsets-with-django/ # Nested formset
def formset_class(self): formset_class = inlineformset_factory( RealTransaction, VirtualTransaction, form=VirtualTransactionForm, formset=BaseModelFormSet, can_delete=True, extra=0, ) return formset_class
def get_formset(self, **kwargs): """Returns a BaseInlineFormSet class for use in admin add/change views.""" if self.exclude is None: exclude = [] else: exclude = list(self.exclude) exclude.extend(self.get_readonly_fields()) if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude: # Take the custom ModelForm's Meta.exclude into account only if the # InlineModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) # if exclude is an empty list we use None, since that's the actual # default exclude = exclude or None can_delete = self.can_delete and self.has_delete_permission() defaults = { "form": self.form, "formset": self.formset, "fk_name": self.fk_name, 'fields': forms.ALL_FIELDS, "exclude": exclude, "formfield_callback": self.formfield_for_dbfield, "extra": self.extra, "max_num": self.max_num, "can_delete": can_delete, } defaults.update(kwargs) return inlineformset_factory(self.parent_model, self.model, **defaults)
def _test_season_formset(self, child_model, formset, fields): inline_formset = inlineformset_factory(Season, child_model, formset=formset, fields=fields, form=AlwaysChangedModelForm, can_delete=True) return inline_formset
def formset(self): formset_class = inlineformset_factory( Question, AnswerOption, form=AnswerOptionForm, formset=I18nFormSet, can_delete=True, extra=0, ) return formset_class( self.request.POST if self.request.method == 'POST' else None, queryset=AnswerOption.objects.filter(question=self.get_object()) if self.get_object() else AnswerOption.objects.none(), event=self.request.event )
def formset(self): formset_class = inlineformset_factory( Submission, Resource, form=ResourceForm, formset=BaseModelFormSet, can_delete=True, extra=0, ) obj = self.get_object() return formset_class( self.request.POST if self.request.method == 'POST' else None, files=self.request.FILES if self.request.method == 'POST' else None, queryset=obj.resources.all() if obj else Resource.objects.none(), prefix='resource', )
def __init__(self, model, widget=FormSetWidget, label=None, initial=None, help_text=None, error_messages=None, show_hidden_initial=False, formset_factory=inlineformset_factory, *args, **kwargs): widget = widget(self) super(FormSetField, self).__init__(required=False, widget=widget, label=label, initial=initial, help_text=help_text, error_messages=error_messages, show_hidden_initial=show_hidden_initial) self.model = model self.formset_factory = formset_factory self.args = args self.kwargs = kwargs
def get_formset(self, **kwargs): """?? BaseInlineFormSet ?""" if self.exclude is None: exclude = [] else: exclude = list(self.exclude) exclude.extend(self.get_readonly_fields()) if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude: # Take the custom ModelForm's Meta.exclude into account only if the # InlineModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) # if exclude is an empty list we use None, since that's the actual # default #exclude = exclude or None can_delete = self.can_delete and self.has_delete_permission() defaults = { "form": self.form, "formset": self.formset, "fk_name": self.fk_name, "exclude": exclude, "formfield_callback": self.formfield_for_dbfield, "extra": self.extra, "max_num": self.max_num, "can_delete": can_delete, } defaults.update(kwargs) return inlineformset_factory(self.parent_model, self.model, **defaults)
def user_profile(request): curr_user = request.user UserProfileInlineFormSet = inlineformset_factory(User, StProfile, form=ProfileForm, extra=2, can_delete=True) if request.method == "POST": form = UserForm(request.POST, request.FILES, instance=curr_user, prefix="main") formset = UserProfileInlineFormSet(request.POST, request.FILES, instance=curr_user, prefix="nested") if form.is_valid() and formset.is_valid(): form.save() formset.save() return HttpResponseRedirect(reverse('home')) else: form = UserForm(instance=curr_user, prefix="main") formset = UserProfileInlineFormSet(instance=curr_user, prefix="nested") return TemplateResponse(request, "registration/profile.html", {"form": form, "formset": formset})
def get_formset(self, **kwargs): """Returns a BaseInlineFormSet class for use in admin add/change views.""" if self.exclude is None: exclude = [] else: exclude = list(self.exclude) exclude.extend(self.get_readonly_fields()) if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude: # Take the custom ModelForm's Meta.exclude into account only if the # InlineModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) # if exclude is an empty list we use None, since that's the actual # default exclude = exclude or None can_delete = self.can_delete and self.has_delete_permission() defaults = { "form": self.form, "formset": self.formset, "fk_name": self.fk_name, "exclude": exclude, "formfield_callback": self.formfield_for_dbfield, "extra": self.extra, "max_num": self.max_num, "can_delete": can_delete, } defaults.update(kwargs) return inlineformset_factory(self.parent_model, self.model, **defaults)
def projectformset(self,*args,**kwargs): if 'initial' in kwargs: extra = len(kwargs['initial']) else: extra = 0 factory = inlineformset_factory( EditorLink, EditorLinkProject, form=forms.EditorLinkProjectForm, can_delete=False, extra=extra ) return factory(*args,**kwargs)
def agent_associations(request, agent_id): agent = get_object_or_404(EconomicAgent, pk=agent_id) HasAssociatesFormSet = inlineformset_factory( EconomicAgent, AgentAssociation, fk_name = "has_associate", form=HasAssociateForm, extra=3, ) has_associates_formset = HasAssociatesFormSet( instance=agent, queryset=agent.all_has_associates(), prefix = "has", data=request.POST or None) IsAssociatesFormSet = inlineformset_factory( EconomicAgent, AgentAssociation, fk_name = "is_associate", form=IsAssociateForm, extra=3, ) is_associates_formset = IsAssociatesFormSet( instance=agent, queryset=agent.all_is_associates(), prefix = "is", data=request.POST or None) if request.method == "POST": #import pdb; pdb.set_trace() keep_going = request.POST.get("keep-going") just_save = request.POST.get("save") for form in has_associates_formset: if form.is_valid(): deleteme = form.cleaned_data['DELETE'] if deleteme: association = form.save(commit=False) if association.id: association.delete() else: form.save() for form in is_associates_formset: if form.is_valid(): deleteme = form.cleaned_data['DELETE'] if deleteme: association = form.save(commit=False) if association.id: association.delete() else: form.save() if just_save: return HttpResponseRedirect('/%s/%s/' % ('accounting/agent', agent.id)) elif keep_going: return HttpResponseRedirect('/%s/%s/' % ('accounting/agent-associations', agent.id)) return render_to_response("valueaccounting/agent_associations.html", { "agent": agent, "has_associates_formset": has_associates_formset, "is_associates_formset": is_associates_formset, "help": get_help("associations"), }, context_instance=RequestContext(request))
def update_concept(request, pk): concept = Concept.objects.get(pk=pk) AlternatesFormSet = inlineformset_factory( Concept, Alternate, can_delete=True, exclude=() ) MispellingsFormSet = inlineformset_factory( Concept, Hidden, can_delete=True, exclude=() ) TagsFormSet = inlineformset_factory( Concept, ConceptTag, can_delete=True, exclude=() ) BroaderFormSet = inlineformset_factory( Concept, Broader, fk_name='concept', can_delete=True, exclude=() ) NarrowerFormSet = inlineformset_factory( Concept, Narrower, fk_name='concept', can_delete=True, exclude=() ) RelatedFormSet = inlineformset_factory( Concept, Related, fk_name='concept', can_delete=True, exclude=() ) if request.POST: concept_form = ConceptForm(request.POST, request.FILES, instance=concept, prefix="concept") alternates_formset = AlternatesFormSet(request.POST, request.FILES, instance=concept, prefix="alternates") misspellings_formset = MispellingsFormSet(request.POST, request.FILES, instance=concept, prefix="misspellings") tags_formset = TagsFormSet(request.POST, request.FILES, instance=concept, prefix="tags") broader_formset = BroaderFormSet(request.POST, request.FILES, instance=concept, prefix="broader") narrower_formset = NarrowerFormSet(request.POST, request.FILES, instance=concept, prefix="narrower") related_formset = RelatedFormSet(request.POST, request.FILES, instance=concept, prefix="related") if concept_form.is_valid() and alternates_formset.is_valid() and tags_formset.is_valid() and broader_formset.is_valid() and narrower_formset.is_valid() and related_formset.is_valid(): concept_form.save() alternates_formset.save() misspellings_formset.save() tags_formset.save() broader_formset.save() narrower_formset.save() related_formset.save() messages.add_message( request, messages.INFO, "Saved concept \"{}\"".format(concept.prefLabel) ) # tag all docs containing concept or one of its aliases tag_concept_and_message_stats(request=request, concept=concept) return HttpResponseRedirect( reverse('thesaurus:detail', args=[pk])) # Redirect after POST pass else: concept_form = ConceptForm(instance=concept, prefix="concept") alternates_formset = AlternatesFormSet(instance=concept, prefix="alternates") misspellings_formset = MispellingsFormSet(instance=concept, prefix="misspellings") tags_formset = TagsFormSet(instance=concept, prefix="tags") broader_formset = BroaderFormSet(instance=concept, prefix="broader") narrower_formset = NarrowerFormSet(instance=concept, prefix="narrower") related_formset = RelatedFormSet(instance=concept, prefix="related") return render(request, 'thesaurus/concept_form.html', {'form': concept_form, 'concept': concept, 'alternates_formset':alternates_formset, 'misspellings_formset':misspellings_formset, 'tags_formset':tags_formset, 'broader_formset':broader_formset, 'narrower_formset':narrower_formset, 'related_formset':related_formset } )