def get_context_data(self, **kwargs): context = super(EntryCreate, self).get_context_data(**kwargs) context['form_helper'] = EntryFormHelper() context['material_formset'] = inlineformset_factory( Entry, EntryMaterial, extra=20, can_delete=False, fields=('material', 'amount', 'role'))(self.request.POST or None) context['custom_material_formset'] = inlineformset_factory( Entry, EntryCustomMaterial, extra=10, can_delete=False, fields=('material', 'amount', 'unit', 'role'))(self.request.POST or None) context['material_formset_helper'] = EntryMaterialFormSetHelper() # Used by JS to view extra fields for free build context['free_build_pk'] = EntryType.objects.get(name__icontains='fribygge').pk return context
def newClient(request): my_client = Client(username=request.user) ContactFormSet = inlineformset_factory(Client, Contact, form=ContactForm, can_delete=False, extra=1) DetailsFormSet = inlineformset_factory(Client, Details, form=DetailsForm, can_delete=False, max_num=1) NegotiationResultFormSet = inlineformset_factory(Client, NegotiationResult, form=NegotiationResultForm, can_delete=False, extra=1) BrandFormSet = inlineformset_factory(Client, Brand, form=BrandForm, can_delete=True, extra=1) PayerFormSet = inlineformset_factory(Client, Payer, form=PayerForm, can_delete=True, extra=1) formClient = ClientForm(request.POST or None, request.FILES or None, instance=my_client) formContactSet = ContactFormSet(request.POST or None, instance=my_client) formDetailsSet = DetailsFormSet(request.POST or None, instance=my_client) formNegotiationResultSet = NegotiationResultFormSet(request.POST or None, instance=my_client) formBrandSet = BrandFormSet(request.POST or None, instance=my_client) formPayerSet = PayerFormSet(request.POST or None, instance=my_client) if formClient.is_valid() and formContactSet.is_valid() and formDetailsSet.is_valid() and formNegotiationResultSet.is_valid() and formBrandSet.is_valid() and formPayerSet.is_valid(): formClient.save() formContactSet.save() formDetailsSet.save() formNegotiationResultSet.save() formBrandSet.save() formPayerSet.save() error(request, 'Информация о клиенте успешно добавлена.') return redirect('client-index') var = {'formClient': formClient, 'formContactSet': formContactSet, 'formDetailsSet': formDetailsSet, 'formNegotiationResultSet': formNegotiationResultSet, 'formBrandSet': formBrandSet, 'formPayerSet': formPayerSet} return render_to_response('client/client/edit.html', var, context_instance=RequestContext(request))
def add(request): '''Adds a Recipe This view follows the create/update pattern for CRUD forms. A GET request returns an empty recipe form, ingredient formset, and recipe_step formset. A valid post creates the recipe object, builds the step and ingredient objects from their respective formsets, and adds the foreign keys references to the recipe. If the forms are not all valid, the function returns attached references to all the forms/formsets. Finally, a GET request with a valid recipe pk will return an attached form/formset for updating the recipe. Args: request: the standard django.http.HttpRequest for all views Returns: django.http.HttpResponse with a context containing a recipe_form, ingredient_formset and recipe_step_formset, or a redirect to the list of recipes Raises: django.http.Http404: recipe_id was given, but not a valid Recipe object ''' IngredientFormSet = inlineformset_factory(Recipe,Ingredient,extra=1, form=IngredientForm) RecipeStepFormSet = inlineformset_factory(Recipe,RecipeStep,extra=1, form=RecipeStepForm) if request.method == 'POST': recipe_form = RecipeForm(request.POST, request.FILES, prefix='recipe') ingredient_formset = IngredientFormSet(request.POST, prefix='ingredients') recipe_step_formset = RecipeStepFormSet(request.POST, prefix='recipe_steps') if recipe_form.is_valid() and ingredient_formset.is_valid()\ and recipe_step_formset.is_valid(): recipe_id = recipe_form.save(commit=False) recipe_id.added_by = request.user recipe_id.save() ingredients = ingredient_formset.save(commit=False) for ingredient in ingredients: ingredient.recipe = recipe_id ingredient.save() recipe_steps = recipe_step_formset.save(commit=False) for recipe_step in recipe_steps: recipe_step.recipe = recipe_id recipe_step.save() return HttpResponseRedirect(reverse('home')) else: recipe_form = RecipeForm(prefix='recipe') ingredient_formset = IngredientFormSet(prefix='ingredients') recipe_step_formset = RecipeStepFormSet(prefix='recipe_steps') return render(request, 'add.html', { 'form_action': reverse('recipe-new'), 'recipe_form' : recipe_form, 'ingredient_formset' : ingredient_formset, 'recipe_step_formset' : recipe_step_formset, })
def newAgency(request): my_agency = AdvertisingAgency(username=request.user) ContactFormSet = inlineformset_factory(AdvertisingAgency, Contact, form=ContactForm, can_delete=False, extra=1) DetailsFormSet = inlineformset_factory(AdvertisingAgency, Details, form=DetailsForm, can_delete=False, max_num=1) NegotiationResultFormSet = inlineformset_factory(AdvertisingAgency, NegotiationResult, form=NegotiationResultForm, can_delete=False, extra=1) BrandFormSet = inlineformset_factory(AdvertisingAgency, Brand, form=BrandForm, can_delete=True, extra=1) PayerFormSet = inlineformset_factory(AdvertisingAgency, Payer, form=PayerForm, can_delete=True, extra=1) formAgency = AgencyForm(request.POST or None, request.FILES or None, instance=my_agency) formContactSet = ContactFormSet(request.POST or None, instance=my_agency) formDetailsSet = DetailsFormSet(request.POST or None, instance=my_agency) formNegotiationResultSet = NegotiationResultFormSet(request.POST or None, instance=my_agency) formBrandSet = BrandFormSet(request.POST or None, instance=my_agency) formPayerSet = PayerFormSet(request.POST or None, instance=my_agency) if formAgency.is_valid() and formContactSet.is_valid() and formDetailsSet.is_valid() and formNegotiationResultSet.is_valid() and formBrandSet.is_valid() and formPayerSet.is_valid(): formAgency.save() formContactSet.save() formDetailsSet.save() formNegotiationResultSet.save() formBrandSet.save() formPayerSet.save() error(request, 'Информация о рекламном агенстве успешно добавлена.') return redirect('agency-index') var = {'formAgency': formAgency, 'formContactSet': formContactSet, 'formDetailsSet': formDetailsSet, 'formNegotiationResultSet': formNegotiationResultSet, 'formBrandSet': formBrandSet, 'formPayerSet': formPayerSet} return render_to_response('client/agency/edit.html', var, context_instance=RequestContext(request))
def lesson_ingredients(request, lesson_id=None): lesson = get_object_or_404(Lesson, pk=lesson_id) if request.user != lesson.teacher: raise PermissionDenied IngredientsDetailsFormset = inlineformset_factory(Lesson, LessonIngredient, form=IngredentsDetailsForm, extra=1, ) ToolFormset = inlineformset_factory(Lesson, LessonTool, form=ToolsDetailsForm, extra=1, ) if request.method == "POST": ingredient_formset = IngredientsDetailsFormset(request.POST, instance=lesson, prefix="ingredients") tool_formset = ToolFormset(request.POST, instance=lesson, prefix="tools") if ingredient_formset.is_valid() and tool_formset.is_valid(): ingredients = ingredient_formset.save() tools = tool_formset.save() if lesson.kind == 1: return HttpResponseRedirect(reverse("lesson_video", kwargs={'lesson_id':lesson.id})) else: return HttpResponseRedirect(reverse("lesson_steps", kwargs={'lesson_id':lesson.id})) else: ingredient_formset = IngredientsDetailsFormset(instance=lesson, prefix="ingredients") tool_formset = ToolFormset(instance=lesson, prefix="tools") return direct_to_template(request, "ingredients_details_form.html", {"ingredient_formset": ingredient_formset, "tool_formset": tool_formset, "lesson": lesson, })
def create_edit(request, rpID): # the 2nd step of 3 phases recipe creation rp = get_object_or_404(Recipe, pk=rpID, ruser=request.user) init_item = 5 IngrdFormSet = inlineformset_factory( Recipe, RecipeIngredients, form=RecipeIngredientForm, extra=init_item, fields=("ingredient", "quantity", "measure"), can_delete=True, ) # IngrdFormSet.clean = clean_ing mthdFormSet = inlineformset_factory( Recipe, RecipeCookmethods, form=RecipeCookmethodForm, extra=init_item, can_delete=True ) if request.method == "POST": ingrdformset = IngrdFormSet(request.POST, instance=rp) mthdformset = mthdFormSet(request.POST, instance=rp) if ingrdformset.is_valid() and mthdformset.is_valid(): ingrdformset.save() mthdformset.save() return HttpResponseRedirect(reverse("recipedia.views.view", args=[rp.pk])) else: ingrdformset = IngrdFormSet(instance=rp) mthdformset = mthdFormSet(instance=rp) gmedia = ingrdformset.forms[0].media + mthdformset.forms[0].media ingrdlist1 = Ingredients.objects.values("id", "name", "category", "measure").extra(order_by=["category"])[:20] return render_to_response( "edit_recipe.html", {"ingrds": ingrdformset, "mthds": mthdformset, "recipe": rp, "ingrdlist1": ingrdlist1, "grpmedia": gmedia}, context_instance=RequestContext(request), )
def course_member_detail(request, slug, member_id): course = get_object_or_404(Course, slug=slug) course_member = get_object_or_404(course.coursemember_set.all(), pk=member_id) TestResultFormset = inlineformset_factory(CourseMember, TestResult, extra=1) CourseMemberAssessmentFormset = inlineformset_factory(CourseMember, CourseMemberAssessment, extra=1) if request.method == "POST": form = CourseMemberForm(request.POST, instance=course_member) test_form = TestResultFormset(request.POST, instance=course_member) assessment_form = CourseMemberAssessmentFormset(request.POST, instance=course_member) if form.is_valid() and test_form.is_valid() and assessment_form.is_valid(): form.save() test_form.save() assessment_form.save() return HttpResponseRedirect(form.instance.get_absolute_url()) else: form = CourseMemberForm(instance=course_member) test_form = TestResultFormset(instance=course_member) assessment_form = CourseMemberAssessmentFormset(instance=course_member) return render_to_response( "courses/course_member_form.html", { "course": course, "form": form, "test_form": test_form, "assessment_form": assessment_form, "member_list": course.coursemember_set.all(), }, context_instance=RequestContext(request), )
def EditarMascota(request, cliente_slug, mascota_slug): instance = Mascota.objects.get(slug=mascota_slug) mascota_form = MascotaForm(request.POST or None, request.FILES or None, instance=instance) VacunaFormSet = inlineformset_factory(Mascota, Vacuna, form=VacunaForm,formset=RequiredBaseInlineFormSet, max_num=10, extra=1) vacuna_formset = VacunaFormSet(request.POST or None, prefix='vacuna',instance=instance) DesparacitanteFormSet = inlineformset_factory(Mascota, Desparacitante, form=DesparacitanteForm,formset=RequiredBaseInlineFormSet, max_num=10, extra=1) desparacitante_formset = DesparacitanteFormSet(request.POST or None, prefix='desparacitante',instance=instance) if mascota_form.is_valid() and vacuna_formset.is_valid() and desparacitante_formset.is_valid(): mascota = mascota_form.save() vacuna = vacuna_formset.save(commit=False) desparacitante = desparacitante_formset.save(commit=False) for v in vacuna: v.mascota = mascota v.save() for d in desparacitante: d.mascota = mascota d.save() messages.add_message(request, messages.INFO, 'Mascota editado correctamente') return HttpResponseRedirect(mascota.get_absolute_url()) context = { 'form': mascota_form, 'vacuna_form':vacuna_formset, 'desparacitante_form':desparacitante_formset, } return render_to_response( 'clinica/crear_mascota.html', context, context_instance = RequestContext(request) )
def edit_cf(request, cf_id): BoolFieldFormSet = inlineformset_factory(CustomForm, BoolField, exclude=('',),can_delete=False,extra=1,form=BoolFieldForm) IntFieldFormSet = inlineformset_factory(CustomForm, IntField, exclude=('',),can_delete=False,extra=1,form=IntFieldForm) cf_obj = CustomForm.objects.get(id=cf_id) init_user={'createdbyuser':request.user} if request.method == 'POST': formform= MkFormForm(request.POST, request.FILES, instance=cf_obj) intformset = IntFieldFormSet(request.POST, request.FILES, instance=cf_obj) boolformset = BoolFieldFormSet(request.POST, request.FILES, instance=cf_obj) if formform.is_valid() and intformset.is_valid() and boolformset.is_valid(): formform.save() for form in intformset: cd = form.cleaned_data if cd.get('fieldlabel'): #this is now a 'name' form.save() for form in boolformset: cd = form.cleaned_data if cd.get('fieldlabel'): #this is now a 'name' form.save() return HttpResponseRedirect(reverse('view_cf', args=(cf_obj.id,))) else: print intformset.errors,boolformset.errors, formform.errors else: formform=MkFormForm(instance=cf_obj,initial=init_user) intformset = IntFieldFormSet(instance=cf_obj) boolformset = BoolFieldFormSet(instance=cf_obj) context = {'intformset':intformset,'boolformset':boolformset,'formform':formform,'cf_id':cf_id} return render(request, 'app/mk_form.html', context)
def NuevaMascota(request, cliente_slug): # def get_cliente(self): # return get_object_or_404(Cliente, slug=self.kwargs.get('cliente_slug')) # def get_initial(self): # initial = super(OrdenVentaForm, self).get_initial() # initial['propietario'] = self.get_propietario() # return initial mascota_form = MascotaForm(request.POST or None, request.FILES or None) VacunaFormSet = inlineformset_factory(Mascota, Vacuna, form=VacunaForm,formset=RequiredBaseInlineFormSet, max_num=10, extra=1) vacuna_formset = VacunaFormSet(request.POST or None, prefix='vacuna') DesparacitanteFormSet = inlineformset_factory(Mascota, Desparacitante, form=DesparacitanteForm,formset=RequiredBaseInlineFormSet, max_num=10, extra=1) desparacitante_formset = DesparacitanteFormSet(request.POST or None, prefix='desparacitante') if mascota_form.is_valid() and vacuna_formset.is_valid() and desparacitante_formset.is_valid(): mascota = mascota_form.save() vacuna = vacuna_formset.save(commit=False) desparacitante = desparacitante_formset.save(commit=False) for v in vacuna: v.mascota = mascota v.save() for d in desparacitante: d.mascota = mascota d.save() messages.add_message(request, messages.INFO, 'Mascota registrado correctamente') return HttpResponseRedirect(mascota.get_absolute_url()) context = { 'form': mascota_form, 'vacuna_form':vacuna_formset, 'desparacitante_form':desparacitante_formset, } return render_to_response( 'clinica/crear_mascota.html', context, context_instance = RequestContext(request) )
def test_non_foreign_key_field(self): """ If the field specified in fk_name is not a ForeignKey, we should get an exception. """ with self.assertRaisesMessage(ValueError, "'inline_formsets.Child' has no field named 'test'."): inlineformset_factory(Parent, Child, fk_name='test')
def test_obsolete_staff_only(self): """ Asserts that obsolete questionnaires are shown to staff members only if they are already selected for a contribution of the Course, and that staff_only questionnaires are always shown. Regression test for #593. """ course = mommy.make(Course) questionnaire = mommy.make(Questionnaire, is_for_contributors=True, obsolete=False, staff_only=False) questionnaire_obsolete = mommy.make(Questionnaire, is_for_contributors=True, obsolete=True, staff_only=False) questionnaire_staff_only = mommy.make(Questionnaire, is_for_contributors=True, obsolete=False, staff_only=True) # The normal and staff_only questionnaire should be shown. contribution1 = mommy.make(Contribution, course=course, contributor=mommy.make(UserProfile), questionnaires=[]) inline_contribution_formset = inlineformset_factory(Course, Contribution, formset=ContributionFormSet, form=ContributionForm, extra=1) formset = inline_contribution_formset(instance=course, form_kwargs={'course': course}) expected = {questionnaire, questionnaire_staff_only} self.assertEqual(expected, set(formset.forms[0].fields['questionnaires'].queryset.all())) self.assertEqual(expected, set(formset.forms[1].fields['questionnaires'].queryset.all())) # Suppose we had an obsolete questionnaire already selected, that should be shown as well. contribution1.questionnaires = [questionnaire_obsolete] inline_contribution_formset = inlineformset_factory(Course, Contribution, formset=ContributionFormSet, form=ContributionForm, extra=1) formset = inline_contribution_formset(instance=course, form_kwargs={'course': course}) expected = {questionnaire, questionnaire_staff_only, questionnaire_obsolete} self.assertEqual(expected, set(formset.forms[0].fields['questionnaires'].queryset.all())) self.assertEqual(expected, set(formset.forms[1].fields['questionnaires'].queryset.all()))
def step_1(request, trial_pk): ct = get_object_or_404(ClinicalTrial, id=int(trial_pk)) if request.POST: form = TrialIdentificationForm(request.POST, instance=ct) SecondaryIdSet = inlineformset_factory(ClinicalTrial, TrialNumber, form=SecondaryIdForm, extra=EXTRA_FORMS) secondary_forms = SecondaryIdSet(request.POST, instance=ct) if form.is_valid() and secondary_forms.is_valid(): form.save() secondary_forms.save() if request.POST.has_key('submit_next'): return HttpResponseRedirect(reverse("step_2",args=[trial_pk])) return HttpResponseRedirect(reverse("repository.edittrial", args=[trial_pk])) else: form = TrialIdentificationForm(instance=ct) SecondaryIdSet = inlineformset_factory(ClinicalTrial, TrialNumber, form=SecondaryIdForm, extra=EXTRA_FORMS, can_delete=True) secondary_forms = SecondaryIdSet(instance=ct) forms = [form] formsets = [secondary_forms] return render_to_response('repository/trial_form.html', {'forms':forms,'formsets':formsets, 'username':request.user.username, 'trial_pk':trial_pk, 'title':TRIAL_FORMS[0], 'steps': step_list(trial_pk), 'next_form_title':_('Sponsors and Sources of Support')})
def edit_voting(request, slug=None): """Create/Edit voting view.""" poll, created = get_or_create_instance(Poll, slug=slug) can_delete_voting = False extra = 0 current_voting_edit = False range_poll_formset = None radio_poll_formset = None if created: poll.created_by = request.user extra = 1 else: if (RangePoll.objects.filter(poll=poll).count() or RadioPoll.objects.filter(poll=poll).count()) == 0: extra = 1 can_delete_voting = True date_now = datetime2pdt() if poll.start < date_now and poll.end > date_now: current_voting_edit = True if current_voting_edit: poll_form = forms.PollEditForm(request.POST or None, instance=poll) else: RangePollFormset = (inlineformset_factory(Poll, RangePoll, formset=forms.BaseRangePollInlineFormSet, extra=extra, can_delete=True)) RadioPollFormset = (inlineformset_factory(Poll, RadioPoll, formset=forms.BaseRadioPollInlineFormSet, extra=extra, can_delete=True)) nominee_list = User.objects.filter( groups__name='Rep', userprofile__registration_complete=True) range_poll_formset = RangePollFormset(request.POST or None, instance=poll, user_list=nominee_list) radio_poll_formset = RadioPollFormset(request.POST or None, instance=poll) poll_form = forms.PollAddForm(request.POST or None, instance=poll, radio_poll_formset=radio_poll_formset, range_poll_formset=range_poll_formset) if poll_form.is_valid(): poll_form.save() if created: messages.success(request, 'Voting successfully created.') else: messages.success(request, 'Voting successfully edited.') return redirect('voting_edit_voting', slug=poll.slug) return render(request, 'edit_voting.html', {'creating': created, 'poll': poll, 'poll_form': poll_form, 'range_poll_formset': range_poll_formset, 'radio_poll_formset': radio_poll_formset, 'can_delete_voting': can_delete_voting, 'current_voting_edit': current_voting_edit})
def get_context_data(self, **kwargs): ctx = super(ReportUpdateView, self).get_context_data(**kwargs) model_class = self.object.root_model.model_class() model_ct = ContentType.objects.get_for_model(model_class) direct_fields = get_direct_fields_from_model(model_class) relation_fields = get_relation_fields_from_model(model_class) DisplayFieldFormset = inlineformset_factory( Report, DisplayField, extra=0, can_delete=True, form=DisplayFieldForm) FilterFieldFormset = inlineformset_factory( Report, FilterField, extra=0, can_delete=True, form=FilterFieldForm) if self.request.POST: ctx['field_list_formset'] = DisplayFieldFormset(self.request.POST, instance=self.object) ctx['field_filter_formset'] = FilterFieldFormset(self.request.POST, instance=self.object, prefix="fil") else: ctx['field_list_formset'] = DisplayFieldFormset(instance=self.object) ctx['field_filter_formset'] = FilterFieldFormset(instance=self.object, prefix="fil") ctx['related_fields'] = relation_fields ctx['fields'] = direct_fields ctx['model_ct'] = model_ct return ctx
def test_staff_only(self): """ Asserts that staff_only questionnaires are shown to Editors only if they are already selected for a contribution of the Course. Regression test for #593. """ course = mommy.make(Course) questionnaire = mommy.make(Questionnaire, is_for_contributors=True, obsolete=False, staff_only=False) questionnaire_obsolete = mommy.make(Questionnaire, is_for_contributors=True, obsolete=True, staff_only=False) questionnaire_staff_only = mommy.make(Questionnaire, is_for_contributors=True, obsolete=False, staff_only=True) # just the normal questionnaire should be shown. contribution1 = mommy.make(Contribution, course=course, contributor=mommy.make(UserProfile), questionnaires=[]) InlineContributionFormset = inlineformset_factory(Course, Contribution, formset=ContributionFormSet, form=EditorContributionForm, extra=1) formset = InlineContributionFormset(instance=course, form_kwargs={'course': course}) expected = set([questionnaire]) self.assertEqual(expected, set(formset.forms[0].fields['questionnaires'].queryset.all())) self.assertEqual(expected, set(formset.forms[1].fields['questionnaires'].queryset.all())) # now a staff member adds a staff only questionnaire, which should be shown as well contribution1.questionnaires = [questionnaire_staff_only] InlineContributionFormset = inlineformset_factory(Course, Contribution, formset=ContributionFormSet, form=EditorContributionForm, extra=1) formset = InlineContributionFormset(instance=course, form_kwargs={'course': course}) expected = set([questionnaire, questionnaire_staff_only]) self.assertEqual(expected, set(formset.forms[0].fields['questionnaires'].queryset.all())) self.assertEqual(expected, set(formset.forms[1].fields['questionnaires'].queryset.all()))
def get_forms(self, extra_forms=[]): AxisFormSet = inlineformset_factory(Subject, Axis, can_delete=False, extra=2, max_num=2) FieldFormSet = inlineformset_factory(Subject, Field, extra=1) data = self.request.POST or None forms = [AxisFormSet(data, instance=self.object), FieldFormSet(data, instance=self.object)] + extra_forms return super(BaseSubjectEdit, self).get_forms(forms)
def update(request, recipe): IngredientFormSet = inlineformset_factory(Recipe, Ingredient, extra=0, form=IngredientForm) RecipeStepFormSet = inlineformset_factory(Recipe, RecipeStep, extra=0, form=RecipeStepForm) recipe = get_object_or_404(Recipe, pk=recipe) if request.method == 'POST': recipe_form = RecipeForm(request.POST, request.FILES, prefix='recipe', instance=recipe) ingredient_formset = IngredientFormSet(request.POST, prefix='ingredients', instance=recipe) recipe_step_formset = RecipeStepFormSet(request.POST, prefix='recipe_steps', instance=recipe) if recipe_form.is_valid() and ingredient_formset.is_valid() and \ recipe_step_formset.is_valid(): recipe_form.save() ingredient_formset.save() recipe_step_formset.save() return HttpResponseRedirect(reverse('home')) else: recipe_form = RecipeForm(instance=recipe, prefix='recipe') ingredient_formset = IngredientFormSet(instance=recipe, prefix='ingredients') recipe_step_formset = RecipeStepFormSet(instance=recipe, prefix='recipe_steps') return render(request, 'add.html', { 'form_action': reverse('recipe-update', args=[recipe.id]), 'recipe_form': recipe_form, 'ingredient_formset': ingredient_formset, 'recipe_step_formset': recipe_step_formset, })
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
def production_add(request, play=None, place=None, company=None): initial = {} if play: initial['play'] = play.id production_form = ProductionForm(data=request.POST or None, initial=initial) # Inline even though empty, because model validation means it can't assign null # to Place.production when calling construct_instance() ProductionPlaceFormSet = inlineformset_factory( Production, ProductionPlace, extra=1, form=PlaceForm ) place_formset = ProductionPlaceFormSet( data = request.POST or None, prefix = 'place', queryset = ProductionPlace.objects.none() ) ProductionCompanyFormSet = inlineformset_factory( Production, Production_Companies, extra=1, form=CompanyInlineForm ) companies_formset = ProductionCompanyFormSet( data = request.POST or None, prefix = 'company', queryset = Production_Companies.objects.none() ) # Yucky, but no way to pass initial to a model formset XXX if place: place_formset.forms[0].initial['place'] = place.id if company: companies_formset.forms[0].initial['productioncompany'] = company.id if request.method == 'POST': if request.POST.get('disregard'): messages.success(request, u"All right, we\u2019ve ignored what you had done.") if play: return HttpResponseRedirect(play.get_absolute_url()) if company: return HttpResponseRedirect(company.get_absolute_url()) if place: return HttpResponseRedirect(place.get_absolute_url()) if production_form.is_valid() and place_formset.is_valid() and companies_formset.is_valid(): # Nasty things to set up the parent/child inline relations as it expects them to be. production = production_form.save() place_formset.instance = production for form in place_formset.forms: form.instance.production = production companies_formset.instance = production for form in companies_formset.forms: form.instance.production = production place_formset.save() companies_formset.save() messages.success(request, "Your addition has been stored; thank you. If you know members of the cast or crew, please feel free to add them now.") url = production.get_edit_cast_url() if request.POST.get('initial_person'): url += '?person=' + request.POST.get('initial_person') return HttpResponseRedirect(url) return render(request, 'productions/add.html', { 'place': place, 'place_formset': place_formset, 'companies_formset': companies_formset, 'play': play, 'company': company, 'form': production_form, })
def bank_register(request): BankSet = modelformset_factory(Bank, exclude=('expired_date',)) ContactorSet = inlineformset_factory(Bank, BankContactor, can_delete=False, max_num=1, exclude=('user', 'bank')) OperatorSet = inlineformset_factory(Bank, BankOperator, extra=1, can_delete=False, max_num=1, exclude=('user', 'bank')) # ContactorSet =modelformset_factory(BankContactor, exclude=('expired_date',)) # OperatorSet = modelformset_factory(BankOperator, exclude=('expired_date',)) operator_formset = OperatorSet() contact_formset = ContactorSet() if not request.method == 'POST': bank_formset = BankForm() else: # contact_formset = ContactorSet(request.POST or None, request.FILES) # operator_formset = OperatorSet(request.POST or None, request.FILES) bank_formset = BankForm(request.POST or None, request.FILES) if bank_formset.is_valid(): # bank_formset.save() return HttpResponse('123123') # if contact_formset.is_valid(): # # contact_formset.save() # return HttpResponse('123123') # if operator_formset.is_valid(): # # operator_formset.save() # return HttpResponse('123123') return render_to_response("member/bank_register.html", { "bank_formset": bank_formset, 'contact_formset': contact_formset, 'operator_formset': operator_formset, "title": u'银行会员注册', }, context_instance=RequestContext(request))
def get_context_data(self, **kwargs): context = super(RegisterOrchestraMemberView, self).get_context_data(**kwargs) context['ticket_form'] = OrchestraMemberRegistrationForm(self.request.POST or None) context['membership_formset'] = inlineformset_factory( Person, OrchestraMembership, min_num=1, max_num=3, extra=2, can_delete=False, form=OrchestraMembershipForm, fields=['orchestra', 'primary'])(self.request.POST or None) context['stuff_formset'] = inlineformset_factory( Person, Holding, extra=self.get_stuff_queryset().count(), can_delete=False, form=OrchestraStuffForm, fields=['product', 'quantity'])(self.request.POST or None, initial=self.get_stuff_formset_initial_data()) context['accept_form'] = AcceptForm(self.request.POST or None) context['person_form_helper'] = PersonFormHelper() context['ticket_form_helper'] = OrchestraTicketFormHelper() context['inline_formset_helper'] = InlineFormSetHelper() context['accept_form_helper'] = AcceptFormHelper() return context
def add_service_ajax(request): detalleServicioFormset = inlineformset_factory(servicios, detalleServicio, extra = 1, can_delete = True, form = detalleServicioForm) estadosServicioFormset = inlineformset_factory(servicios, servicioTieneEstados, extra = 1, can_delete = False, form = servicioTieneEstadosForm) tiposervicioFormset = inlineformset_factory(servicios, servicioTieneTipoServicio, extra = 1, can_delete = False, form = servicioTieneTipoServicioForm) #servicioTieneProductoFormset = inlineformset_factory(servicios, servicioTieneProducto, extra = 1, can_delete = False, form = servicioProductoForm) servicioTienePerfilFormset = inlineformset_factory(servicios, servicioTienePerfil, extra = 1, can_delete = False, form = servicioTecnicoForm) if request.method == 'POST': serviceForm = servicioForm(request.POST) if serviceForm.is_valid(): servicio = serviceForm.save(commit = False) if request.is_ajax(): #realizamos una copia de todos los datos que vienen por POST copia = request.POST.copy() #modificamos el campo TOTAL_FORM copia ['servicios detalle-TOTAL_FORMS'] = int(copia['servicios detalle-TOTAL_FORMS']) + 1 detalleFormset = detalleServicioFormset(copia, instance = servicio) estadoFormset = estadosServicioFormset(request.POST, instance = servicio) tiposerFormset = tiposervicioFormset(request.POST, instance = servicio) #mantFormset = tiposMantenimientoFormset(request.POST, instance = servicio) tecnicoserFormset = servicioTienePerfilFormset(request.POST, instance = servicio) #productoFormset = servicioTieneProductoFormset(request.POST, instance = servicio) else: print ('serviceForm no valido') template = 'addEquipos.html' return render_to_response(template, context_instance = RequestContext(request, locals()))
def test_manager_only(self): """ Asserts that manager_only questionnaires are shown to Editors only if they are already selected for a contribution of the Evaluation. Regression test for #593. """ evaluation = mommy.make(Evaluation) questionnaire = mommy.make(Questionnaire, type=Questionnaire.CONTRIBUTOR, obsolete=False, manager_only=False) questionnaire_manager_only = mommy.make(Questionnaire, type=Questionnaire.CONTRIBUTOR, obsolete=False, manager_only=True) # one obsolete questionnaire that should never be shown mommy.make(Questionnaire, type=Questionnaire.CONTRIBUTOR, obsolete=True, manager_only=False) # just the normal questionnaire should be shown. contribution1 = mommy.make(Contribution, evaluation=evaluation, contributor=mommy.make(UserProfile), questionnaires=[]) InlineContributionFormset = inlineformset_factory(Evaluation, Contribution, formset=ContributionFormSet, form=EditorContributionForm, extra=1) formset = InlineContributionFormset(instance=evaluation, form_kwargs={'evaluation': evaluation}) expected = set([questionnaire]) self.assertEqual(expected, set(formset.forms[0].fields['questionnaires'].queryset.all())) self.assertEqual(expected, set(formset.forms[1].fields['questionnaires'].queryset.all())) # now a manager adds a manager only questionnaire, which should be shown as well contribution1.questionnaires.set([questionnaire_manager_only]) InlineContributionFormset = inlineformset_factory(Evaluation, Contribution, formset=ContributionFormSet, form=EditorContributionForm, extra=1) formset = InlineContributionFormset(instance=evaluation, form_kwargs={'evaluation': evaluation}) expected = set([questionnaire, questionnaire_manager_only]) self.assertEqual(expected, set(formset.forms[0].fields['questionnaires'].queryset.all())) self.assertEqual(expected, set(formset.forms[1].fields['questionnaires'].queryset.all()))
def cadastrar(request, filme_id=None): filme = None if filme_id is None else ( get_object_or_404(Filme, id=int(filme_id))) if request.method == 'POST': CreditosInlineSet = inlineformset_factory(Filme, Credito, extra=3) if filme is None: form_filme = FilmeForm(request.POST) else: form_filme = FilmeForm(request.POST, instance=filme) if form_filme.is_valid(): filme = form_filme.save() forms_creditos = CreditosInlineSet(request.POST, instance=filme) if forms_creditos.is_valid(): creditos = forms_creditos.save() return HttpResponseRedirect(filme.get_absolute_url()) if filme is None: # preparar para criar novo filme form_filme = FilmeForm() CreditosInlineSet = inlineformset_factory(Filme, Credito, extra=3, can_delete=False) forms_creditos = CreditosInlineSet() else: # caso contrário, preparar para editar um filme existente form_filme = FilmeForm(instance=filme) CreditosInlineSet = inlineformset_factory(Filme, Credito, extra=3, can_delete=True) forms_creditos = CreditosInlineSet(instance=filme) forms = dict(form_filme=form_filme, forms_creditos=forms_creditos) return render_to_response('demofilmes/filme_cadastro.html', forms)
def test_obsolete_manager_only(self): """ Asserts that obsolete questionnaires are shown to managers only if they are already selected for a contribution of the Evaluation, and that manager only questionnaires are always shown. Regression test for #593. """ evaluation = mommy.make(Evaluation) questionnaire = mommy.make(Questionnaire, type=Questionnaire.CONTRIBUTOR, obsolete=False, manager_only=False) questionnaire_obsolete = mommy.make(Questionnaire, type=Questionnaire.CONTRIBUTOR, obsolete=True, manager_only=False) questionnaire_manager_only = mommy.make(Questionnaire, type=Questionnaire.CONTRIBUTOR, obsolete=False, manager_only=True) # The normal and manager_only questionnaire should be shown. contribution1 = mommy.make(Contribution, evaluation=evaluation, contributor=mommy.make(UserProfile), questionnaires=[]) inline_contribution_formset = inlineformset_factory(Evaluation, Contribution, formset=ContributionFormSet, form=ContributionForm, extra=1) formset = inline_contribution_formset(instance=evaluation, form_kwargs={'evaluation': evaluation}) expected = {questionnaire, questionnaire_manager_only} self.assertEqual(expected, set(formset.forms[0].fields['questionnaires'].queryset.all())) self.assertEqual(expected, set(formset.forms[1].fields['questionnaires'].queryset.all())) # Suppose we had an obsolete questionnaire already selected, that should be shown as well. contribution1.questionnaires.set([questionnaire_obsolete]) inline_contribution_formset = inlineformset_factory(Evaluation, Contribution, formset=ContributionFormSet, form=ContributionForm, extra=1) formset = inline_contribution_formset(instance=evaluation, form_kwargs={'evaluation': evaluation}) expected = {questionnaire, questionnaire_manager_only, questionnaire_obsolete} self.assertEqual(expected, set(formset.forms[0].fields['questionnaires'].queryset.all())) self.assertEqual(expected, set(formset.forms[1].fields['questionnaires'].queryset.all()))
def questionnaire_copy(request, questionnaire_id): if request.method == "POST": questionnaire = Questionnaire() InlineQuestionFormset = inlineformset_factory( Questionnaire, Question, formset=AtLeastOneFormSet, form=QuestionForm, extra=1, exclude=("questionnaire",) ) form = QuestionnaireForm(request.POST, instance=questionnaire) formset = InlineQuestionFormset(request.POST.copy(), instance=questionnaire, save_as_new=True) if form.is_valid() and formset.is_valid(): form.save() formset.save() messages.success(request, _("Successfully created questionnaire.")) return redirect("staff:questionnaire_index") else: return render(request, "staff_questionnaire_form.html", dict(form=form, formset=formset)) else: questionnaire = get_object_or_404(Questionnaire, id=questionnaire_id) InlineQuestionFormset = inlineformset_factory( Questionnaire, Question, formset=IdLessQuestionFormSet, form=QuestionForm, extra=1, exclude=("questionnaire",), ) form = QuestionnaireForm(instance=questionnaire) formset = InlineQuestionFormset(instance=Questionnaire(), queryset=questionnaire.question_set.all()) return render(request, "staff_questionnaire_form.html", dict(form=form, formset=formset))
def mostra_dados_projeto(request, codigo): usuario = request.user projeto = get_object_or_404(Projeto, pk=codigo) IntegranteFormSet = inlineformset_factory(Projeto, Integrante,extra = 2) ProfessorFormSet = inlineformset_factory(Projeto, Professor,extra = 2) codigo = projeto.codProj if request.method == 'POST': f = ProjetoModelForm(request.POST, instance=projeto) if f.is_valid(): project = f.save(commit=False) formset = IntegranteFormSet(request.POST, instance=project) formset2 = ProfessorFormSet(request.POST, instance=project) if formset.is_valid(): c = f.save() d = formset.save() e = formset2.save() return HttpResponseRedirect('/') else: return render_to_response(form.errors) else: return render_to_response(form.errors) else: f = ProjetoModelForm(instance=projeto) formset = IntegranteFormSet(instance=projeto) formset2 = ProfessorFormSet(instance=projeto) return render_to_response('alterar_dados.html', {'formset':formset,'formset2':formset2,'form':f, 'codigo':codigo,'usuario':usuario,},context_instance=RequestContext(request))
def manage_fichas(request): from django.forms.models import inlineformset_factory FichaFormSet = inlineformset_factory(Empresa, Ficha, extra = 1) VisitaFormSet = inlineformset_factory(Empresa, Visita, extra = 1) empresa = Empresa.objects.get(id = 1) if request.method == 'POST': formempresa = FormEmpresa(request.POST, request.FILES, instance = empresa) formset = FichaFormSet(request.POST, request.FILES, instance = empresa) formsetvisita = VisitaFormSet(request.POST, request.FILES, instance = empresa) if (formempresa.is_valid() and formset.is_valid() and formsetvisita.is_valid()): formempresa.save() #if formset.is_valid(): formset.save() formsetvisita.save() return HttpResponseRedirect("/fichas/") else: formempresa = FormEmpresa(instance = empresa) formset = FichaFormSet(instance = empresa) formsetvisita = VisitaFormSet(instance = empresa) return render_to_response("ficha_form.html", locals() # {"formset": formset, # "formempresa": formempresa, # } )
def update_own_user(request): if request.method == "POST": user_form = HsUserForm(request.POST, prefix='user', instance=request.user) WebLinkFormset = inlineformset_factory(HsUser, WebLink) link_formset = WebLinkFormset(request.POST, request.FILES, instance=request.user, prefix="link") if user_form.is_valid() and link_formset.is_valid(): user_form.save() link_formset.save() messages.success(request, 'Bilgileriniz güncellendi.') return redirect(request.user.get_absolute_url()) else: user_form = HsUserForm(instance=request.user, prefix="user") WebLinkFormset = inlineformset_factory(HsUser, WebLink) link_formset = WebLinkFormset(instance=request.user, prefix="link") return render_to_response('members/hsuser_form.html', {'user_form': user_form, 'link_formset': link_formset}, context_instance=RequestContext(request) )
from fgallery.models import Album, Photo from fgallery.widgets import AdminImageWidget class AlbumForm(forms.ModelForm): class Meta: model = Album fields = ('title', 'slug') class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = ( 'image', 'title', ) widgets = { 'image': AdminImageWidget(), } PhotoFormSet = formset_factory(PhotoForm) EditPhotoFormSet = inlineformset_factory(Album, Photo, form=PhotoForm, fields=( 'image', 'title', ))
def clean(self): """Checks that all uncertainty-factor types are unique.""" if any(self.errors): return ufs = [] for form in self.forms: uf = form.cleaned_data['uf_type'] if uf in ufs: raise ValidationError("Uncertainty-factors must be unique for" "a given reference-value.") ufs.append(uf) UFRefValFormSet = inlineformset_factory(models.ReferenceValue, models.UncertaintyFactorRefVal, form=UncertaintyFactorRefValForm, formset=Base_UFRefVal_FormSet, extra=0, can_delete=False) class SpeciesForm(ModelForm): class Meta: model = models.Species fields = '__all__' def __init__(self, *args, **kwargs): kwargs.pop('parent', None) super(SpeciesForm, self).__init__(*args, **kwargs) def clean_name(self): return self.cleaned_data['name'].title()
)) previous_timestamp = None for form in _forms: timestamp = form.cleaned_data['timestamp'] if previous_timestamp: if timestamp <= previous_timestamp: raise forms.ValidationError( _('Timestamps must be distinct')) previous_timestamp = timestamp RecordingTimestampFormSet = inlineformset_factory( Recording, RecordingTimestamp, formset=BaseRecordingTimestampFormSet, form=RecordingTimestampForm, extra=1, can_delete=1, ) class PopoloImportForm(forms.Form): location = forms.URLField(label=_('Location of Popolo JSON data')) def __init__(self, instance=None, *args, **kwargs): super(PopoloImportForm, self).__init__(*args, **kwargs) self.instance = instance def clean(self): cleaned_data = super(PopoloImportForm, self).clean()
def edit_event(request, slug=None, clone=None): """Edit event view.""" initial = {} extra_formsets = 2 event, created = get_or_create_instance(Event, slug=slug) if created: event.owner = request.user initial = { 'country': request.user.userprofile.country, 'city': request.user.userprofile.city, 'region': request.user.userprofile.region, 'timezone': request.user.userprofile.timezone } else: # This is for backwards compatibility for all the events # that were set before the change in the minutes section # of the drop down widget to multiples of 5. # Start time: Floor rounding # End time: Ceilling rounding event.start -= timedelta(minutes=event.start.minute % 5) if (event.end.minute % 5) != 0: event.end += timedelta(minutes=(5 - (event.end.minute % 5))) if event.eventmetricoutcome_set.exists(): extra_formsets = 0 editable = False if request.user.groups.filter(name='Admin').count(): editable = True # Compatibility code for old metrics min_forms = 0 metrics_form = forms.EventMetricsForm event_form = forms.EventForm(request.POST or None, editable_owner=editable, instance=event, initial=initial, clone=clone, user=request.user) if event.has_new_metrics or clone: min_forms = 2 if event.is_past_event and not clone: metrics_form = forms.PostEventMetricsForm event_form = forms.PostEventForm(request.POST or None, editable_owner=editable, instance=event, initial=initial) EventMetricsFormset = inlineformset_factory( Event, Event.metrics.through, form=metrics_form, formset=forms.BaseEventMetricsFormset, extra=extra_formsets) EventMetricsFormset.form = staticmethod(curry(metrics_form, clone=clone)) metrics_formset = EventMetricsFormset(request.POST or None, instance=event, min_forms=min_forms, clone=clone) if event_form.is_valid() and metrics_formset.is_valid(): event_form.save() if created: messages.success(request, 'Event successfully created.') statsd.incr('events.create_event') elif clone: messages.success(request, 'Event successfully created.') statsd.incr('events.clone_event') else: messages.success(request, 'Event successfully updated.') statsd.incr('events.edit_event') metrics_formset.save() return redirect('events_view_event', slug=event_form.instance.slug) can_delete_event = False if (not created and (event.owner == request.user or request.user.has_perm('events.can_delete_events'))): can_delete_event = True return render( request, 'edit_event.html', { 'creating': created, 'event': event, 'event_form': event_form, 'metrics_formset': metrics_formset, 'can_delete_event': can_delete_event })
def new_post(request): BlogSlugFormSet = inlineformset_factory( Post, Post_Slugs, can_delete=True, extra=3, fields=('slug', 'is_active'), formset=CustomBlogSlugInlineFormSet) if request.method == 'POST': blog_form = BlogpostForm(request.POST) blogslugs_formset = BlogSlugFormSet(request.POST) if blog_form.is_valid() and blogslugs_formset.is_valid(): blog_post = blog_form.save(commit=False) blogslugs_formset = BlogSlugFormSet(request.POST, instance=blog_post) if blogslugs_formset.is_valid(): blog_post.user = request.user if request.POST.get('meta_description'): blog_post.meta_description = request.POST[ 'meta_description'] blog_post.status = 'D' if request.POST.get('status') == "P": if request.user.user_roles == "Admin" or request.user.is_special or request.user.is_superuser: blog_post.status = 'P' if not blog_post.published_on: blog_post.published_on = datetime.datetime.now( ).date() elif request.POST.get('status') == "T": if request.user.user_roles == "Admin" or request.user.is_special or request.user.is_superuser: blog_post.status = 'T' elif request.POST.get('status') == "R": blog_post.status = 'R' blog_post.save() blogslugs_formset.save() # If no slugs are specified, then create one using title. if not blog_post.slugs.all(): blog_post.create_blog_slug([slugify(blog_post.title)]) blog_post.check_and_activate_slug() if request.POST.get('tags', ''): tags = request.POST.get('tags') tags = tags.split(',') for tag in tags: blog_tag = Tags.objects.filter(name=tag) if blog_tag: blog_tag = blog_tag[0] else: blog_tag = Tags.objects.create(name=tag) blog_post.tags.add(blog_tag) sg = sendgrid.SendGridClient(settings.SG_USER, settings.SG_PWD) sending_msg = sendgrid.Mail() sending_msg.set_subject("New blog post has been created") blog_url = 'https://www.micropyramid.com/blog/' + \ str(blog_post.slug) + '/' message = '<p>New blog post has been created by ' + str( request.user) + ' with the name ' + str( blog_post.title) + ' in the category ' + str( blog_post.category.name) + '.</p>' sending_msg.set_html(message) sending_msg.set_text('New blog post has been created') sending_msg.set_from(request.user.email) sending_msg.add_to([ user.email for user in User.objects.filter(is_admin=True) ]) sg.send(sending_msg) cache._cache.flush_all() return redirect(reverse('micro_blog:admin_post_list')) else: blog_form = BlogpostForm() blogslugs_formset = BlogSlugFormSet(instance=Post()) categories = Category.objects.all() c = {} c.update(csrf(request)) return render( request, 'admin/blog/blog-new.html', { 'categories': categories, 'csrf_token': c['csrf_token'], 'blogslugs_formset': blogslugs_formset, 'blog_form': blog_form })
return self.instance class WebConferenceUpdateForm(WebconferenceForm): def clean_start(self): return self.cleaned_data['start'] class SettingsForm(forms.ModelForm): class Meta: model = ConferenceSettings fields = ['domain'] labels = { 'domain': _('Domain'), } help_texts = { 'domain': _('The domain of the jitsi server, e.g. meet.jit.si'), } InlinePendenciesFormset = inlineformset_factory(Webconference, Pendencies, form=PendenciesLimitedForm, extra=1, max_num=3, validate_max=True, can_delete=True)
from photo.models import Album, Photo from django.forms.models import inlineformset_factory PhotoInlineFormSet = inlineformset_factory(Album, Photo, fields= ['image', 'title', 'description'], extra=2)
# If not tracking stock, we hide the fields if not product_class.track_stock: del self.fields['num_in_stock'] del self.fields['low_stock_threshold'] else: self.fields['price_excl_tax'].required = True self.fields['num_in_stock'].required = True class Meta: model = StockRecord exclude = ('product', 'num_allocated') BaseStockRecordFormSet = inlineformset_factory(Product, StockRecord, form=StockRecordForm, extra=1) class StockRecordFormSet(BaseStockRecordFormSet): def __init__(self, product_class, user, *args, **kwargs): self.user = user self.require_user_stockrecord = not user.is_staff self.product_class = product_class super(StockRecordFormSet, self).__init__(*args, **kwargs) self.set_initial_data() def set_initial_data(self): """ If user has only one partner associated, set the first stock record's partner to it. Can't pre-select for staff users as
return None if not self.initial.get('object_id'): return None return self.initial.get('content_type').get_object_for_this_type( pk=self.initial.get('object_id')) rating = forms.TypedChoiceField( choices=[], widget=RatingRadioSelect(attrs={'class': 'rating-input'}), coerce=int) class Meta: model = Tag fields = ('rating', 'content_type', 'object_id') widgets = { 'content_type': forms.HiddenInput(), 'object_id': forms.HiddenInput(), } def __init__(self, prompt_instance=None, *args, **kwargs): super(TagForm, self).__init__(*args, **kwargs) self.fields['rating'].choices = prompt_instance.prompt.generate_scale() ResponseTagsForm = inlineformset_factory(Response, Tag, form=TagForm, can_delete=False, extra=0)
submitted_file=field_value, submitted_at=datetime.datetime.now(), latest=True) new_submission.save() return True class AssessmentMarkForm(forms.ModelForm): class Meta: model = AssessmentMark fields = ('mark',) exclude = ('rubric_mark',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) max_mark = self.instance.rubric_mark.max_mark mark_title = self.instance.rubric_mark.title self.fields["mark"].label = ( f"{mark_title} (out of {str(max_mark)})") self.fields["mark"].required = True self.fields["mark"].widget.attrs["class"] = "form-control" self.fields["mark"].widget.attrs["min"] = "0" self.fields["mark"].widget.attrs["max"] = str(max_mark) self.fields["mark"].widget.attrs["onkeyup"] = "mlc(this)" self.fields["mark"].widget.attrs["placeholder"] = "__/" + str(max_mark) AssessmentMarksFormSet = inlineformset_factory(Assessment, AssessmentMark, extra=0, can_delete=False, fields=('mark',), form=AssessmentMarkForm)
} class PDAInstanceForm(ModelForm): class Meta: model = PDAInstance fields = ('pda_type', 'description', 'date_completed', 'pages', 'clock_hours', 'ceu', 'file') widgets = { 'file': forms.FileInput(attrs={'size': 1}), } PDAInstanceFormSet = inlineformset_factory(PDARecord, PDAInstance, form=PDAInstanceForm, extra=1, can_delete=False) #class PDAInstanceFormSetHelper(FormHelper): # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.form_method = 'post' # self.layout = Layout( # 'pda_type', # 'description','date_completed', # 'pages', 'clock_hours', 'ceu', 'file' # ) # self.render_required_fields = True
match = re.match(url_pattern_re, identifier) if match: identifier = match.groups()[0] validator = ExternalAccount.ACCOUNT_TYPES[account_type].get( 'validator') if validator: identifier = validator(identifier) cleaned_data['identifier'] = identifier return cleaned_data AccountsFormset = inlineformset_factory(UserProfile, ExternalAccount, form=ExternalAccountForm, extra=1) class IdpProfileForm(happyforms.ModelForm): """Form for the IdpProfile model.""" class Meta: model = IdpProfile fields = ['privacy'] IdpProfileFormset = inlineformset_factory(UserProfile, IdpProfile, form=IdpProfileForm, extra=0)
# -*- encoding: utf-8 -*- from django.contrib.auth.models import User from django import forms from models import Reparacion, ReparacionLinea from django.forms.formsets import formset_factory from django.forms.models import inlineformset_factory from apps.manager.models import Sucursal from apps.inventory.models import Articulo from apps.sales.models import Cliente class ReparacionForm(forms.ModelForm): class Meta: model = Reparacion id_reparacion = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'span1'})) total = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control pull-right','style':'margin-top:6px; margin-right:6px;','value':'0','readonly':'true'})) comentario = forms.CharField(widget=forms.Textarea(attrs={'rows':'2'})) class ReparacionLineaForm(forms.ModelForm): class Meta: model = ReparacionLinea id_reparacion = forms.IntegerField(widget=forms.HiddenInput()) articulo = forms.ModelChoiceField(widget=forms.Select,queryset=Articulo.objects.all().filter(is_active=True,tipo=2),initial=None) total_linea = forms.IntegerField(widget=forms.NumberInput(attrs={'value':'0','readonly':'true'})) ReparacionLineaFormset = inlineformset_factory(Reparacion, ReparacionLinea, form=ReparacionLineaForm, extra=1)
from django import forms from django.forms.models import inlineformset_factory from .models import Course, Module, Subscription ModuleFormSet = inlineformset_factory(Course, Module, fields=['title', 'description'], extra=3, can_delete=True) class SubscriptionForm(forms.ModelForm): class Meta: model = Subscription fields = [ 'your_email', ] """This is the ModuleFormSet formset. We build it using the inlineformset_factory() function provided by Django. Inline formsets is a small abstraction on top of formsets that simplifies working with related objects. This function allows us to build a model formset dynamically for the Module objects related to a Course object. We use the following parameters to build the formset: • fields: The fields that will be included in each form of the formset. • extra: Allows us to set up the number of empty extra forms to display in the formset. • can_delete: If you set this to True, Django will include a Boolean field for
from django import forms from django.forms.models import inlineformset_factory from api.models import Questionnaire, Question AnswerFormSet = inlineformset_factory(Questionnaire, Question, exclude=('question', ), extra=0, can_delete=False) class QuestionnaireForm(forms.ModelForm): class Meta: model = Questionnaire fields = ('questionnaire_name', ) class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ( 'questionnaire', 'question_text', )
def layer_metadata(request, layername, template='layers/layer_metadata.html'): layer = _resolve_layer(request, layername, 'base.change_resourcebase_metadata', _PERMISSION_MSG_METADATA) layer_attribute_set = inlineformset_factory( Layer, Attribute, extra=0, form=LayerAttributeForm, ) topic_category = layer.category poc = layer.poc metadata_author = layer.metadata_author if request.method == "POST": if layer.metadata_uploaded_preserve: # layer metadata cannot be edited out = { 'success': False, 'errors': METADATA_UPLOADED_PRESERVE_ERROR } return HttpResponse(json.dumps(out), content_type='application/json', status=400) layer_form = LayerForm(request.POST, instance=layer, prefix="resource") attribute_form = layer_attribute_set( request.POST, instance=layer, prefix="layer_attribute_set", queryset=Attribute.objects.order_by('display_order')) category_form = CategoryForm( request.POST, prefix="category_choice_field", initial=int(request.POST["category_choice_field"]) if "category_choice_field" in request.POST else None) else: layer_form = LayerForm(instance=layer, prefix="resource") attribute_form = layer_attribute_set( instance=layer, prefix="layer_attribute_set", queryset=Attribute.objects.order_by('display_order')) category_form = CategoryForm( prefix="category_choice_field", initial=topic_category.id if topic_category else None) if request.method == "POST" and layer_form.is_valid( ) and attribute_form.is_valid() and category_form.is_valid(): new_poc = layer_form.cleaned_data['poc'] new_author = layer_form.cleaned_data['metadata_author'] if new_poc is None: if poc is None: poc_form = ProfileForm(request.POST, prefix="poc", instance=poc) else: poc_form = ProfileForm(request.POST, prefix="poc") if poc_form.is_valid(): if len(poc_form.cleaned_data['profile']) == 0: # FIXME use form.add_error in django > 1.7 errors = poc_form._errors.setdefault( 'profile', ErrorList()) errors.append( _('You must set a point of contact for this resource')) poc = None if poc_form.has_changed and poc_form.is_valid(): new_poc = poc_form.save() if new_author is None: if metadata_author is None: author_form = ProfileForm(request.POST, prefix="author", instance=metadata_author) else: author_form = ProfileForm(request.POST, prefix="author") if author_form.is_valid(): if len(author_form.cleaned_data['profile']) == 0: # FIXME use form.add_error in django > 1.7 errors = author_form._errors.setdefault( 'profile', ErrorList()) errors.append( _('You must set an author for this resource')) metadata_author = None if author_form.has_changed and author_form.is_valid(): new_author = author_form.save() new_category = TopicCategory.objects.get( id=category_form.cleaned_data['category_choice_field']) for form in attribute_form.cleaned_data: la = Attribute.objects.get(id=int(form['id'].id)) la.description = form["description"] la.attribute_label = form["attribute_label"] la.visible = form["visible"] la.display_order = form["display_order"] la.save() if new_poc is not None and new_author is not None: new_keywords = [ x.strip() for x in layer_form.cleaned_data['keywords'] ] layer.keywords.clear() layer.keywords.add(*new_keywords) the_layer = layer_form.save() up_sessions = UploadSession.objects.filter(layer=the_layer.id) if up_sessions.count( ) > 0 and up_sessions[0].user != the_layer.owner: up_sessions.update(user=the_layer.owner) the_layer.poc = new_poc the_layer.metadata_author = new_author Layer.objects.filter(id=the_layer.id).update(category=new_category) if getattr(settings, 'SLACK_ENABLED', False): try: from geonode.contrib.slack.utils import build_slack_message_layer, send_slack_messages send_slack_messages( build_slack_message_layer("layer_edit", the_layer)) except: print "Could not send slack message." return HttpResponseRedirect( reverse('layer_detail', args=(layer.service_typename, ))) if poc is not None: layer_form.fields['poc'].initial = poc.id poc_form = ProfileForm(prefix="poc") poc_form.hidden = True else: poc_form = ProfileForm(prefix="poc") poc_form.hidden = False if metadata_author is not None: layer_form.fields['metadata_author'].initial = metadata_author.id author_form = ProfileForm(prefix="author") author_form.hidden = True else: author_form = ProfileForm(prefix="author") author_form.hidden = False return render_to_response( template, RequestContext( request, { "layer": layer, "layer_form": layer_form, "poc_form": poc_form, "author_form": author_form, "attribute_form": attribute_form, "category_form": category_form, }))
def Create(request): if request.user.is_authenticated(): if request.GET.get('t'): tagname = request.GET.get('t').strip() if tagname: try: tag = Tag.objects.filter(name=tagname)[:1].get() except Tag.DoesNotExist: tag = None else: tag = None else: tagname = None tag = None if request.method == 'GET': if request.GET.get('t') == '': return redirect('/i/create/') content = {'tagname': tagname} return render(request, 'item/create.html', content) if request.method == 'POST': if ((not request.POST.get('content') or request.POST.get('content').strip() == '') and (not request.FILES or 'VCAP_SERVICES' in os.environ)): content = {} return render(request, 'item/create.html', content) form = ItemContentForm(request.POST) if form.is_valid(): ItemContentInlineFormSet = inlineformset_factory( ItemContent, ContentAttachment, form=ItemContentForm) for attachmentfile in request.FILES.getlist('file'): attachmentform = ContentAttachmentForm( request.POST, request.FILES) if attachmentform.is_valid(): pass else: content = {'form': form} return render(request, 'item/create.html', content) item = Item(user=request.user) item.save() itemcontent = ItemContent(item=item) itemcontentform = ItemContentForm(request.POST, instance=itemcontent) itemcontent = itemcontentform.save() itemcontent.save() if tagname: if not tag: tag = Tag() tag.name = tagname tag.save() item.tag.add(tag) item.save() if 'VCAP_SERVICES' not in os.environ: #attach save for attachmentfile in request.FILES.getlist('file'): attachment = ContentAttachment(itemcontent=itemcontent) attachmentform = ContentAttachmentForm( request.POST, request.FILES, instance=attachment) if attachmentform.is_valid(): contentattachment = attachmentform.save() contentattachment.title = attachmentfile.name contentattachment.contenttype = str( attachmentfile.content_type) contentattachment.save() #convert img to svg img2svg(contentattachment) x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') ip = request.META['REMOTE_ADDR'] if x_forwarded_for: ip = x_forwarded_for.split(', ')[-1] itemcontent.ip = ip itemcontent.ua = request.META['HTTP_USER_AGENT'] itemcontent.save() else: content = {'item': item, 'reply': reply, 'form': form} return render(request, 'item/create.html', content) return redirect('/i/' + str(item.id) + '/') else: return redirectlogin(request)
def layer_metadata(request, layername, template='layers/layer_metadata.html'): layer = _resolve_layer(request, layername, 'layers.change_layer', _PERMISSION_MSG_METADATA) layer_attribute_set = inlineformset_factory(Layer, Attribute, extra=0, form=LayerAttributeForm, ) poc = layer.poc metadata_author = layer.metadata_author ContactRole.objects.get(resource=layer, role=layer.poc_role) ContactRole.objects.get(resource=layer, role=layer.metadata_author_role) if request.method == "POST": layer_form = LayerForm(request.POST, instance=layer, prefix="layer") attribute_form = layer_attribute_set(request.POST, instance=layer, prefix="layer_attribute_set", queryset=Attribute.objects.order_by('display_order')) else: layer_form = LayerForm(instance=layer, prefix="layer") attribute_form = layer_attribute_set(instance=layer, prefix="layer_attribute_set", queryset=Attribute.objects.order_by('display_order')) if request.method == "POST" and layer_form.is_valid() and attribute_form.is_valid(): new_poc = layer_form.cleaned_data['poc'] new_author = layer_form.cleaned_data['metadata_author'] new_keywords = layer_form.cleaned_data['keywords'] if new_poc is None: poc_form = ProfileForm(request.POST, prefix="poc") if poc_form.has_changed and poc_form.is_valid(): new_poc = poc_form.save() if new_author is None: author_form = ProfileForm(request.POST, prefix="author") if author_form.has_changed and author_form.is_valid(): new_author = author_form.save() for form in attribute_form.cleaned_data: la = Attribute.objects.get(id=int(form['id'].id)) la.description = form["description"] la.attribute_label = form["attribute_label"] la.visible = form["visible"] la.display_order = form["display_order"] la.save() if new_poc is not None and new_author is not None: the_layer = layer_form.save() the_layer.poc = new_poc the_layer.metadata_author = new_author the_layer.keywords.clear() the_layer.keywords.add(*new_keywords) return HttpResponseRedirect(reverse('layer_detail', args=(layer.typename,))) if poc.user is None: poc_form = ProfileForm(instance=poc, prefix="poc") else: layer_form.fields['poc'].initial = poc.id poc_form = ProfileForm(prefix="poc") poc_form.hidden=True if metadata_author.user is None: author_form = ProfileForm(instance=metadata_author, prefix="author") else: layer_form.fields['metadata_author'].initial = metadata_author.id author_form = ProfileForm(prefix="author") author_form.hidden=True return render_to_response(template, RequestContext(request, { "layer": layer, "layer_form": layer_form, "poc_form": poc_form, "author_form": author_form, "attribute_form": attribute_form, }))
def View(request, id): try: item = Item.objects.filter(useritemrelationship__isnull=True).filter( Q(belong__isnull=True)).get(id=id) #itemcontent = ItemContent.objects.filter(item=item) itemcontent = item.itemcontent_set.all() #取第一个内容首行作为标题 #if itemcontent[0].content: # item.title = itemcontent[0].content.strip().splitlines()[0] #else: # contentattachment = itemcontent[0].contentattachment_set.all() # if contentattachment: # item.title = contentattachment[0].title # else: # item.title = str(item.id) #item.firstcontent = ''.join(itemcontent[0].content.strip().splitlines(True)[1:]) #取最后一个内容首行作为标题 if itemcontent.last().content: item.title = itemcontent.last().content.strip().splitlines()[0] else: contentattachment = itemcontent.last().contentattachment_set.all() if contentattachment: item.title = contentattachment[0].title else: item.title = str(item.id) item.firstcontent = ''.join( itemcontent.last().content.strip().splitlines(True)[1:]) except Item.DoesNotExist: item = None if not item: return redirect('/') try: items = item.get_all_items(include_self=False) items.sort(key=lambda item: item.create, reverse=False) paginator = Paginator(items, 100) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) except Item.DoesNotExist: items = None if request.method == 'GET': try: UserNotify.objects.filter(user=request.user.id).filter( item=item).delete() UserNotify.objects.filter(user=request.user.id).filter( item__in=set(item.id for item in items)).delete() except UserNotify.DoesNotExist: pass reply = None if request.GET.get('reply'): replyid = str(request.GET.get('reply')) try: reply = Item.objects.get(id=replyid) except UserNotify.DoesNotExist: pass if not item or (item.status == 'private' and item.user != request.user): content = {'item': None} return render(request, 'item/view.html', content) try: tags = Tag.objects.all().order_by('?')[:10] except Tag.DoesNotExist: tags = None content = {'item': item, 'items': items, 'reply': reply, 'tags': tags} return render(request, 'item/view.html', content) if request.method == 'POST': if not item or (item.status == 'private' and item.user != request.user): content = {'item': None} return render(request, 'item/view.html', content) if request.user.is_authenticated(): #把信息改为只有私有 if request.user.id == 1 and request.POST.get( 'status') == 'private': item.status = 'private' item.save() return redirect('/') if item.user == request.user and request.POST.get('tagname'): tagname = request.POST.get('tagname').strip() if tagname != '': if request.POST.get('operate') == 'remove': try: tags = Tag.objects.filter(name=tagname).all() for tag in tags: item.tag.remove(tag) item.save() except: pass else: try: tag = Tag.objects.filter(name=tagname)[:1].get() except Tag.DoesNotExist: tag = Tag() tag.name = tagname tag.save() if tag not in item.tag.all(): item.tag.add(tag) item.save() if request.POST.get('type') == 'json': content = str(tag.id) return HttpResponse( json.dumps(content, encoding='utf-8', ensure_ascii=False, indent=4), content_type="application/json; charset=utf-8") return redirect('/i/' + id + '/') reply = None if request.POST.get('reply'): replyid = str(request.POST.get('reply')) try: reply = Item.objects.get(id=replyid) except UserNotify.DoesNotExist: pass if (not request.POST.get('content') or request.POST.get('content').strip() == '') and ( not request.FILES or 'VCAP_SERVICES' in os.environ): content = {'item': item, 'items': items, 'reply': reply} return render(request, 'item/view.html', content) form = ItemContentForm(request.POST) if form.is_valid(): ItemContentInlineFormSet = inlineformset_factory( ItemContent, ContentAttachment, form=ItemContentForm) for attachmentfile in request.FILES.getlist('file'): attachmentform = ContentAttachmentForm( request.POST, request.FILES) if attachmentform.is_valid(): pass else: content = { 'item': item, 'items': items, 'reply': reply, 'form': form } return render(request, 'item/view.html', content) new_item = Item(user=request.user) new_item.save() if reply: new_item.belong.add(reply) else: new_item.belong.add(item) itemcontent = ItemContent(item=new_item) itemcontentform = ItemContentForm(request.POST, instance=itemcontent) itemcontent = itemcontentform.save() itemcontent.save() if 'VCAP_SERVICES' not in os.environ: #attach save for attachmentfile in request.FILES.getlist('file'): attachment = ContentAttachment(itemcontent=itemcontent) attachmentform = ContentAttachmentForm( request.POST, request.FILES, instance=attachment) if attachmentform.is_valid(): contentattachment = attachmentform.save() contentattachment.title = attachmentfile.name contentattachment.contenttype = str( attachmentfile.content_type) contentattachment.save() #convert img to svg img2svg(contentattachment) x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') ip = request.META['REMOTE_ADDR'] if x_forwarded_for: ip = x_forwarded_for.split(', ')[-1] itemcontent.ip = ip itemcontent.ua = request.META['HTTP_USER_AGENT'] itemcontent.save() if reply: if request.user != reply.user: notify = UserNotify(user=reply.user, item=new_item) notify.save() else: if request.user != item.user: notify = UserNotify(user=item.user, item=new_item) notify.save() return redirect('/i/' + id + '/#' + str(new_item.id)) else: content = {'item': item, 'reply': reply, 'form': form} return render(request, 'item/view.html', content) else: return redirectlogin(request)
def Update(request, id): if request.user.is_authenticated(): try: item = Item.objects.filter( useritemrelationship__isnull=True).filter( Q(belong__isnull=True)).get(id=id) if item.user.username != request.user.username: item = None else: itemcontent = item.itemcontent_set.all() #取第一个内容首行作为标题 #if itemcontent[0].content: # item.title = itemcontent[0].content.strip().splitlines()[0] #else: # contentattachment = itemcontent[0].contentattachment_set.all() # if contentattachment: # item.title = contentattachment[0].title # else: # item.title = str(item.id) #item.firstcontent = ''.join(itemcontent[0].content.strip().splitlines(True)[1:]) #取最后一个内容首行作为标题 if itemcontent.last().content: item.title = itemcontent.last().content.strip().splitlines( )[0] else: contentattachment = itemcontent.last( ).contentattachment_set.all() if contentattachment: item.title = contentattachment[0].title else: item.title = str(item.id) item.firstcontent = ''.join( itemcontent.last().content.strip().splitlines(True)[1:]) except Item.DoesNotExist: item = None if not item: return redirect('/i/' + id) if request.method == 'GET': content = {'item': item} return render(request, 'item/update.html', content) if request.method == 'POST': if item: if request.POST.get('content').strip() == '' and ( not request.FILES or 'VCAP_SERVICES' in os.environ): content = {'item': item} return render(request, 'item/update.html', content) form = ItemContentForm(request.POST) if form.is_valid(): ItemContentInlineFormSet = inlineformset_factory( ItemContent, ContentAttachment, form=ItemContentForm) for attachmentfile in request.FILES.getlist('file'): attachmentform = ContentAttachmentForm( request.POST, request.FILES) if attachmentform.is_valid(): pass else: content = {'item': item, 'form': form} return render(request, 'item/update.html', content) itemcontent = ItemContent(item=item) itemcontentform = ItemContentForm(request.POST, instance=itemcontent) itemcontent = itemcontentform.save() itemcontent.save() if 'VCAP_SERVICES' not in os.environ: #attach save for attachmentfile in request.FILES.getlist('file'): attachment = ContentAttachment( itemcontent=itemcontent) attachmentform = ContentAttachmentForm( request.POST, request.FILES, instance=attachment) if attachmentform.is_valid(): contentattachment = attachmentform.save() contentattachment.title = attachmentfile.name contentattachment.contenttype = str( attachmentfile.content_type) contentattachment.save() #convert img to svg img2svg(contentattachment) x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') ip = request.META['REMOTE_ADDR'] if x_forwarded_for: ip = x_forwarded_for.split(', ')[-1] itemcontent.ip = ip itemcontent.ua = request.META['HTTP_USER_AGENT'] itemcontent.save() return redirect('/i/' + id) else: content = {'form': form} return render(request, 'item/update.html', content) else: return redirect('/i/' + id) else: return redirect('/u/login/?next=/i/update/' + id)
def edit_coordinator(request, coordinator): history = History.objects.filter( submitter=request.user, job=coordinator).order_by('-submission_date') DatasetFormSet = inlineformset_factory(Coordinator, Dataset, form=DatasetForm, max_num=0, can_order=False, can_delete=True) DataInputFormSet = inlineformset_factory(Coordinator, DataInput, form=DataInputForm, max_num=0, can_order=False, can_delete=True) DataInputFormSet.form = staticmethod( curry(DataInputForm, coordinator=coordinator)) DataOutputFormSet = inlineformset_factory(Coordinator, DataOutput, form=DataOutputForm, max_num=0, can_order=False, can_delete=True) DataOutputFormSet.form = staticmethod( curry(DataOutputForm, coordinator=coordinator)) dataset = Dataset(coordinator=coordinator) dataset_form = DatasetForm(instance=dataset, prefix='create') NewDataInputFormSet = inlineformset_factory(Coordinator, DataInput, form=DataInputForm, extra=0, can_order=False, can_delete=False) NewDataInputFormSet.form = staticmethod( curry(DataInputForm, coordinator=coordinator)) NewDataOutputFormSet = inlineformset_factory(Coordinator, DataOutput, form=DataOutputForm, extra=0, can_order=False, can_delete=False) NewDataOutputFormSet.form = staticmethod( curry(DataOutputForm, coordinator=coordinator)) if request.method == 'POST': coordinator_form = CoordinatorForm(request.POST, instance=coordinator, user=request.user) dataset_formset = DatasetFormSet(request.POST, request.FILES, instance=coordinator) data_input_formset = DataInputFormSet(request.POST, request.FILES, instance=coordinator) data_output_formset = DataOutputFormSet(request.POST, request.FILES, instance=coordinator) new_data_input_formset = NewDataInputFormSet(request.POST, request.FILES, instance=coordinator, prefix='input') new_data_output_formset = NewDataOutputFormSet(request.POST, request.FILES, instance=coordinator, prefix='output') if coordinator_form.is_valid() and dataset_formset.is_valid() and data_input_formset.is_valid() and data_output_formset.is_valid() \ and new_data_input_formset.is_valid() and new_data_output_formset.is_valid(): coordinator = coordinator_form.save() dataset_formset.save() data_input_formset.save() data_output_formset.save() new_data_input_formset.save() new_data_output_formset.save() request.info(_('Coordinator saved.')) return redirect( reverse('oozie:edit_coordinator', kwargs={'coordinator': coordinator.id})) else: coordinator_form = CoordinatorForm(instance=coordinator, user=request.user) dataset_formset = DatasetFormSet(instance=coordinator) data_input_formset = DataInputFormSet(instance=coordinator) data_output_formset = DataOutputFormSet(instance=coordinator) new_data_input_formset = NewDataInputFormSet( queryset=DataInput.objects.none(), instance=coordinator, prefix='input') new_data_output_formset = NewDataOutputFormSet( queryset=DataOutput.objects.none(), instance=coordinator, prefix='output') return render( 'editor/edit_coordinator.mako', request, { 'coordinator': coordinator, 'coordinator_form': coordinator_form, 'dataset_formset': dataset_formset, 'data_input_formset': data_input_formset, 'data_output_formset': data_output_formset, 'dataset': dataset, 'dataset_form': dataset_form, 'new_data_input_formset': new_data_input_formset, 'new_data_output_formset': new_data_output_formset, 'history': history })
class Meta: model = Campaign fields = ('connection_message', ) class CampaignStepForm(forms.ModelForm): step_time = forms.ChoiceField( widget=forms.Select(attrs=css_form_attrs), choices=STEP_TIMES, ) textarea_css['placeholder'] = 'Send your welcome message to the contact' message = forms.CharField(label=_('Welcome Message'), widget=forms.Textarea(attrs=textarea_css)) class Meta: model = CampaignStep fields = ( 'step_time', 'message', ) InlineCampaignStepFormSet = inlineformset_factory(Campaign, CampaignStep, form=CampaignStepForm, fields=('step_time', 'message'), extra=1, can_delete=True)
super(AddMenuBaseFormSet, self).__init__(*args, **kwargs) def get_formset_extra_kwargs(self, kwargs): extra_kwargs = { 'request': kwargs.pop('request', None), } return extra_kwargs def _construct_form(self, i, **kwargs): kwargs.update(self.extra_kwargs) return super(AddMenuBaseFormSet, self)._construct_form(i, **kwargs) def clean(self): name_list = [] for form in self.forms: name = form.cleaned_data.get('name', None) if name in name_list: raise forms.ValidationError(_('Duplicate Data')) else: name_list.append(name) AddMenuFormSet = inlineformset_factory( Restaurant, Menu, form=AddMenuForm, formset=AddMenuBaseFormSet, extra=2, ) AddMenuFormSet.helper = InlineFormsetHelper()
def edit_coordinator(request, coordinator): history = History.objects.filter( submitter=request.user, job=coordinator).order_by('-submission_date') DatasetFormSet = inlineformset_factory(Coordinator, Dataset, form=DatasetForm, max_num=0, can_order=False, can_delete=True) DataInputFormSet = inlineformset_factory(Coordinator, DataInput, form=DataInputForm, max_num=0, can_order=False, can_delete=True) DataInputFormSet.form = staticmethod( curry(DataInputForm, coordinator=coordinator)) DataOutputFormSet = inlineformset_factory(Coordinator, DataOutput, form=DataOutputForm, max_num=0, can_order=False, can_delete=True) DataOutputFormSet.form = staticmethod( curry(DataOutputForm, coordinator=coordinator)) dataset = Dataset(coordinator=coordinator) dataset_form = DatasetForm(instance=dataset, prefix='create') NewDataInputFormSet = inlineformset_factory(Coordinator, DataInput, form=DataInputForm, extra=0, can_order=False, can_delete=False) NewDataInputFormSet.form = staticmethod( curry(DataInputForm, coordinator=coordinator)) NewDataOutputFormSet = inlineformset_factory(Coordinator, DataOutput, form=DataOutputForm, extra=0, can_order=False, can_delete=False) NewDataOutputFormSet.form = staticmethod( curry(DataOutputForm, coordinator=coordinator)) enable_cron_scheduling = ENABLE_CRON_SCHEDULING.get() if request.method == 'POST': coordinator_form = CoordinatorForm(request.POST, instance=coordinator, user=request.user) dataset_formset = DatasetFormSet(request.POST, request.FILES, instance=coordinator) data_input_formset = DataInputFormSet(request.POST, request.FILES, instance=coordinator) data_output_formset = DataOutputFormSet(request.POST, request.FILES, instance=coordinator) new_data_input_formset = NewDataInputFormSet(request.POST, request.FILES, instance=coordinator, prefix='input') new_data_output_formset = NewDataOutputFormSet(request.POST, request.FILES, instance=coordinator, prefix='output') if coordinator_form.is_valid() and dataset_formset.is_valid() and data_input_formset.is_valid() and data_output_formset.is_valid() \ and new_data_input_formset.is_valid() and new_data_output_formset.is_valid(): coordinator = coordinator_form.save() dataset_formset.save() data_input_formset.save() data_output_formset.save() new_data_input_formset.save() new_data_output_formset.save() coordinator.sla = json.loads(request.POST.get('sla')) if enable_cron_scheduling: coordinator.cron_frequency = { 'frequency': request.POST.get('cron_frequency'), 'isAdvancedCron': request.POST.get('isAdvancedCron') == 'on' } coordinator.save() request.info(_('Coordinator saved.')) return redirect( reverse('oozie:edit_coordinator', kwargs={'coordinator': coordinator.id})) else: coordinator_form = CoordinatorForm(instance=coordinator, user=request.user) dataset_formset = DatasetFormSet(instance=coordinator) data_input_formset = DataInputFormSet(instance=coordinator) data_output_formset = DataOutputFormSet(instance=coordinator) new_data_input_formset = NewDataInputFormSet( queryset=DataInput.objects.none(), instance=coordinator, prefix='input') new_data_output_formset = NewDataOutputFormSet( queryset=DataOutput.objects.none(), instance=coordinator, prefix='output') return render( 'editor/edit_coordinator.mako', request, { 'coordinator': coordinator, 'coordinator_form': coordinator_form, 'dataset_formset': dataset_formset, 'data_input_formset': data_input_formset, 'data_output_formset': data_output_formset, 'dataset': dataset, 'dataset_form': dataset_form, 'new_data_input_formset': new_data_input_formset, 'new_data_output_formset': new_data_output_formset, 'history': history, 'coordinator_frequency': json.dumps(coordinator.cron_frequency), 'enable_cron_scheduling': enable_cron_scheduling, })
def add_report(request): dict = {} AddSaleFormSet = inlineformset_factory( Institution, InstitutionPurchase, exclude=['report', 'institution', 'timeStamp'], extra=1) AddScopeFormSet = inlineformset_factory(Institution, InstitutionFurtherPurchase, exclude=['report', 'institution'], extra=1) new_sale = AddSaleFormSet(prefix='sale') new_scope = AddScopeFormSet(prefix='scope') form = ReportForm() if request.POST: form = ReportForm(request.POST) if 'add_sale' in request.POST: cp = request.POST.copy() new_sale = AddSaleForm(request.POST) cp['sale-TOTAL_FORMS'] = int(cp['sale-TOTAL_FORMS']) + 1 new_sale = AddSaleFormSet(cp, prefix='sale') new_scope = AddScopeFormSet(cp, prefix='scope') elif 'add_scope' in request.POST: cp = request.POST.copy() new_scope = AddScopeForm(request.POST) cp['scope-TOTAL_FORMS'] = int(cp['scope-TOTAL_FORMS']) + 1 new_sale = AddSaleFormSet(cp, prefix='sale') new_scope = AddScopeFormSet(cp, prefix='scope') elif form.is_valid(): data = form.cleaned_data salesperson = request.user institution = Institution.objects.get( name__iexact=data['institution']) q = Report.objects.filter(salesperson=salesperson, institution=institution, date=data['date']) if q.count() > 0: messages.add_message(request, messages.INFO, "The Report Already Exists.") else: report = Report() report.salesperson = salesperson report.institution = institution report.date = data['date'] report.meeting_note = data['meeting_note'] report.stage_of_negotiation = data[ 'stage_of_negotiation'].capitalize() report.timeStamp = datetime.now() report.save() sale_formset = AddSaleFormSet(request.POST, request.FILES, prefix='sale') if sale_formset.is_valid(): for form in sale_formset: temp = form.save(commit=False) temp.report = report temp.institution = institution temp.timeStamp = datetime.now() temp.save() scope_formset = AddScopeFormSet(request.POST, request.FILES, prefix='scope') if scope_formset.is_valid(): for form in scope_formset: temp = form.save(commit=False) temp.report = report temp.institution = institution temp.save() form = ReportForm() messages.add_message( request, messages.INFO, "You have successfully added a new report.") dict['form'] = form dict['sale'] = new_sale dict['scope'] = new_scope return render_to_response('report/add_report.html', dict, context_instance=RequestContext(request))
def edit_blog_post(request, blog_slug): blog_post = get_object_or_404(Post, slugs__slug=blog_slug) active_slug = blog_post.slug old_blog_status = blog_post.status if active_slug != blog_slug: return redirect( reverse('micro_blog:edit_blog_post', kwargs={'blog_slug': active_slug})) if not blog_post.is_editable_by(request.user): return render_to_response('admin/accessdenied.html') BlogSlugFormSet = inlineformset_factory( Post, Post_Slugs, can_delete=True, extra=3, fields=('slug', 'is_active'), formset=CustomBlogSlugInlineFormSet) if request.method == 'POST': blog_form = BlogpostForm(request.POST, instance=blog_post) blogslugs_formset = BlogSlugFormSet(request.POST, instance=blog_post) if blog_form.is_valid() and blogslugs_formset.is_valid(): blog_post = blog_form.save(commit=False) if blogslugs_formset.is_valid(): blog_post.status = old_blog_status blog_post.meta_description = request.POST.get( 'meta_description') if request.POST.get('status') == "P": if request.user.user_roles == "Admin" or request.user.is_special or request.user.is_superuser: blog_post.status = 'P' elif request.POST.get('status') == "T": if request.user.user_roles == "Admin" or request.user.is_special or request.user.is_superuser: blog_post.status = 'T' elif (request.POST.get('status') == "R" or request.POST.get('status') == "D"): blog_post.status = request.POST.get('status') else: pass blog_post.save() blogslugs_formset.save() # If no slugs are specified, then create one using title. if not blog_post.slugs.all(): blog_post.create_blog_slug([slugify(blog_post.title)]) blog_post.check_and_activate_slug() blog_post.tags.clear() if request.POST.get('tags', ''): for tag in blog_post.tags.all(): blog_post.tags.remove(tag) tags = request.POST.get('tags') tags = tags.split(',') for tag in tags: blog_tag = Tags.objects.filter(name=tag) if blog_tag: blog_tag = blog_tag[0] else: blog_tag = Tags.objects.create(name=tag) blog_post.tags.add(blog_tag) cache._cache.flush_all() return redirect(reverse('micro_blog:admin_post_list')) else: blog_form = BlogpostForm(instance=blog_post) blogslugs_formset = BlogSlugFormSet(instance=blog_post) categories = Category.objects.all() c = {} c.update(csrf(request)) return render( request, 'admin/blog/blog-edit.html', { 'blog_post': blog_post, 'categories': categories, 'csrf_token': c['csrf_token'], 'blogslugs_formset': blogslugs_formset, 'blog_form': blog_form })
from django.http import Http404 # import logging from sufix.models import Partners, PartnerDetails, PartnersDescriptions, Contacts from sufix.models import Docs4Projects, DocStatus4Projects, DocStatusAdd4Projects, DocType4Projects, DocsDescription4Projects, Orders from partners.forms import PartnerForm # logger = logging.getLogger(__name__) PartnerDetailsFormset = inlineformset_factory(Partners, PartnerDetails, can_delete=False, extra=1, fields='__all__', widgets={ 'details_of_bank': Textarea(attrs={ 'cols': 65, 'rows': 4 }), }) PartnerDescriptionFormset = inlineformset_factory(Partners, PartnersDescriptions, can_delete=False, extra=1, fields=['description'], widgets={ 'description': Textarea(attrs={ 'cols': 65,
balance = Decimal(0) for form in self.forms: if form.cleaned_data.get('DELETE'): continue balance += form.cleaned_data.get('balance_delta', 0) if balance != 0: raise forms.ValidationError("The total amount of Credits must be " "equal to the total amount of Debits.") return #: A FormSet for :class:`Transactions<.models.Transaction>`, derived from the #: :class:`BaseTransactionFormSet`. TransactionFormSet = inlineformset_factory(JournalEntry, Transaction, extra=20, form=TransactionForm, formset=BaseTransactionFormSet, can_delete=True) @parsleyfy class TransferForm(BaseEntryForm, forms.Form): """ A form for Transfer Entries, a specialized :class:`~.models.JournalEntry`. Transfer Entries move a discrete :attr:`amount` between two :class:`Accounts<accounts.models.Account>`. The :attr:`source` is debited while the :attr:`destination` is credited. .. attribute:: source
def get_context_data(self, **kwargs): ctx = super(EditPostView, self).get_context_data(**kwargs) if defaults.PYBB_ATTACHMENT_ENABLE and (not 'aformset' in kwargs): AttachmentFormSet = inlineformset_factory(Post, Attachment, extra=1, form=AttachmentForm) ctx['aformset'] = AttachmentFormSet(instance=self.object) return ctx
goods = goods.order_by("price", "name") else: if self.order == "D": goods = goods.order_by("-name") else: goods = goods.order_by("name") return goods class GoodDetailView(PageNumberView, DetailView, SortMixin, PageNumberMixin): model = Good template_name = "good.html" GoodImagesFormset = inlineformset_factory(Good, GoodImage, fields="__all__", can_order=True) class GoodCreate(PermissionRequiredMixin, PageNumberView, TemplateView, SortMixin, PageNumberMixin): permission_required = 'goods.add_good' template_name = "good_add.html" cat = None form = None formset = None def get(self, request, *args, **kwargs): if self.kwargs["pk"] is None: self.cat = Category.objects.first() else: