def submit_task(request): LOG.debug("Task submit view requested") ArgumentFormSet = formset_factory(ArgumentForm) EnvironmentFormSet = formset_factory(EnvironmentForm) # Process data if POST if request.method == 'POST': task_form = TaskForm(request.POST) if task_form.is_valid(): task_name = task_form.cleaned_data['task_name'] task_remote = task_form.cleaned_data['remote'] task_id = api.submit_task(task_name, {}, [], task_remote) return HttpResponseRedirect('/tasks/' + str(task_id)) else: task_form = TaskForm() argument_formset = ArgumentFormSet(prefix='fs1') environment_formset = EnvironmentFormSet(prefix='fs2') context = { 'form': task_form, 'arg_formset': argument_formset, 'env_formset': environment_formset, } return render(request, 'submit.html', context)
def get_resume_forms(user, resume): forms = [] basic_data_form = BasicResumeForm(initial=resume.get_basic_details()) edu_form = ResumeEducationForm() experience_form = ResumeExperienceForm() SkillFormSet = formset_factory(ResumeSkillForm, extra=0) skill_form_set = SkillFormSet(prefix='skills', initial=resume.get_skills_details()) LanguageFormSet = formset_factory(ResumeLanguageForm, extra=0) language_form_set = LanguageFormSet(prefix='languages', initial=resume.get_languages_details()) HobbyFormSet = formset_factory(ResumeHobbyForm, extra=0) hobby_form_set = HobbyFormSet(prefix='hobbies', initial=resume.get_hobbies_details()) ExperienceFormSet = formset_factory(ResumeExperienceForm, extra=0) experience_form_set = ExperienceFormSet(prefix='experiences', initial=resume.get_experience_details()) EducationFormSet = formset_factory(ResumeEducationForm, extra=0) education_form_set = EducationFormSet(prefix='educations', initial=resume.get_education_details()) forms.append(basic_data_form) forms.append(language_form_set) forms.append(education_form_set) forms.append(experience_form_set) forms.append(skill_form_set) forms.append(hobby_form_set) return forms
def input_amc_scores(request, grade="2nd", classroom="Trost"): if request.method == 'POST': TestListFormSet = formset_factory(forms.InputAMCScores, extra=0) formset = TestListFormSet(request.POST) has_errors = False for form in formset: # Seems like it should be possible to have the form know the instance it was created from, and update # that rather than go through this manual process if form.is_valid(): form.save() else: existing_results = AMCTestResult.objects.filter(student=form.instance.student, date_tested=form.instance.date_tested) if form.instance.score and existing_results.count(): instance = existing_results.first() instance.score = form.instance.score instance.save() else: has_errors = True print(form.errors) messages.add_message(request, messages.SUCCESS, "American Math Challenges Recorded!") if not has_errors: url = reverse('amc:classlist', kwargs={'grade': grade, 'classroom': classroom}) return HttpResponseRedirect(url) else: student_list = StudentRoster.objects.filter(current_class__grade=grade) \ .filter(current_class__teacher__last_name=classroom) form_count = student_list.count() TestListFormSet = formset_factory(forms.InputAMCScores, extra=form_count) formset = TestListFormSet() # Would be nice to create forms from the instances rather than manually set initial, but that did not seem # to work correctly for i in range(form_count): today = datetime.date.today() existing_results = AMCTestResult.objects.filter(student=student_list[i], date_tested=today) initial_test = brain_extras.current_amc_test(student_list[i]) if existing_results.count(): instance = existing_results.first() formset.forms[i].instance = instance initial_student = instance.student initial_score = instance.score else: initial_student = student_list[i] initial_score = None formset.forms[i].fields['student'].initial = initial_student formset.forms[i].fields['test'].initial = initial_test formset.forms[i].fields['score'].initial = initial_score return render(request, 'amc/input_amc_scores_form.html', { 'formset': formset, 'classroom': classroom, 'grade': grade, })
def add_rmc_account(request, site_id): """ This view is for adding a new rmc account to the database and associate it with a site """ site = Sesh_Site.objects.filter(id=site_id).first() # sensors formset factories emonThFormSetFactory = formset_factory(SensorEmonThForm) emonTxFormSetFactory = formset_factory(SensorEmonTxForm) bmvFormSetFactory = formset_factory(SensorBMVForm) # formsets emonth_form_set = emonThFormSetFactory(prefix="emonth") emontx_form_set = emonTxFormSetFactory(prefix="emontx") bmv_form_set = bmvFormSetFactory(prefix="bmv") # emonpi form site_emonpi = Sensor_EmonPi.objects.filter(site=site).first() emonpi_form = SensorEmonPiForm(prefix='emonpi', instance=site_emonpi) context_dict = {} rmc_form = RMCForm() if request.method == 'POST': rmc_form = RMCForm(request.POST) emonpi_form = SensorEmonPiForm(request.POST, prefix='emonpi', instance=site_emonpi) emonth_form_set = emonThFormSetFactory(request.POST, prefix="emonth") emontx_form_set = emonTxFormSetFactory(request.POST, prefix="emontx") bmv_form_set = bmvFormSetFactory(request.POST, prefix="bmv") sensors_sets = [emonth_form_set, emontx_form_set, bmv_form_set] if rmc_form.is_valid(): rmc_account = rmc_form.save(commit=False) rmc_account.site = site rmc_account.save() associate_sensors_sets_to_site(sensors_sets, site) if emonpi_form.is_valid(): emonpi_form.save() return redirect('index') context_dict['rmc_form'] = rmc_form context_dict['emonpi_form'] = emonpi_form context_dict['site_id'] = site_id context_dict['sensors_list'] = SENSORS_LIST context_dict['emonth_form'] = emonThFormSetFactory(prefix="emonth") context_dict['emontx_form'] = emonTxFormSetFactory(prefix="emontx") context_dict['bmv_form'] = bmvFormSetFactory(prefix="bmv") return render(request, 'seshdash/add_rmc_account.html', context_dict)
def get(self, request, *args, **kwargs): """ Creates a formset for creating medication entry records for a specified patient. Value for [patient] is taken from request URI. If a medication ID is provided in URI, retrieves medication entries from database for update :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() logger.info('Retrieving patient ID from request URI') patient_id = request.GET.get('patient') logger.info('Retrieving medication record ID from request URI') medication_id = kwargs.get('id') if patient_id: logger.info('Retrieved patient ID value [%s]' % patient_id) patient = Patient.objects.get(pk=int(patient_id)) logger.info('Creating formset with 1 extra form') MedicationFormSet = formset_factory(self.form_class) formset = MedicationFormSet() response = render(request, self.template_name, {'formset': formset, 'patient': patient, 'submit_label': 'Record'}) elif medication_id: logger.info('Retrieved medication record ID value [%s]' % medication_id) medication = Medication.objects.get(pk=medication_id) logger.info('Retrieving medication entries using medication record ID [%s]' % medication.id) medication_entries = MedicationEntry.objects.filter(medication=medication) initial = [] logger.info('Pre-filling formset using medication entry records retrieved from database') for entry in medication_entries: initial.append({'description': entry.description, 'dosage': entry.dosage, 'package': entry.package, 'frequency': entry.frequency, 'designated_time': entry.designated_time}) logger.info('Creating formset with no additional forms') MedicationFormSet = formset_factory(self.form_class, extra=0) formset = MedicationFormSet(initial=initial) response = render(request, self.template_name, {'formset': formset, 'patient': medication.patient, 'submit_label': 'Record'}) else: logger.warn('Did not receive value for required medical parameter') response = redirect(DASHBOARD_PAGE_NAME, permanent=True) log_end_time() return response
def PaymentsView(request): P_list = [] PM_list = [] try: Payments = list(PaymentModel.objects.all().values()) except: Payments = [] try: PaymModes = list(PaymModeModel.objects.all().values()) except: PaymModes = [] PaymentsFormset = formset_factory( PaymentForm, extra=1) PaymModesFormset = formset_factory( PaymModeForm, extra=1) if request.method == 'POST': payments_formset = PaymentsFormset(request.POST, prefix='pfs') paymmodes_formset = PaymModesFormset(request.POST, prefix='pmfs') for payment_form in payments_formset: if payment_form.is_valid(): paymCode = payment_form.cleaned_data.get('PaymCode') if paymCode: payment = payment_form.save() P_list.append(payment.pk) pl = PaymentModel.objects.all() pl.exclude(pk__in=list(P_list)).delete() for paymmode_form in paymmodes_formset: if paymmode_form.is_valid(): paymModeCode = paymmode_form.cleaned_data.get('PaymModeCode') if paymModeCode: paymmode = paymmode_form.save() PM_list.append(paymmode.pk) pml = PaymModeModel.objects.all() pml.exclude(pk__in=list(PM_list)).delete() messages.success( request, 'Pagos creados correctamente') else: payments_formset = PaymentsFormset(initial=Payments, prefix='pfs') paymmodes_formset = PaymModesFormset(initial=PaymModes, prefix='pmfs') return render_to_response('Payment/ManagePayments.html', {'payments_formset': payments_formset, 'paymmodes_formset': paymmodes_formset, }, context_instance=RequestContext(request))
def quote_form(request, object_id, slug): topic = get_object_or_404(models.Topic, pk=object_id) ArgumentFormSet = formset_factory( forms.ArgumentForm, min_num=0, max_num=3, extra=3, validate_min=True, validate_max=True, ) if request.method == 'POST': source_form = forms.SourceForm(request.POST) source_form.full_clean() source = source_form.cleaned_data form = forms.CombinedForms( source=source_form, quote=forms.QuoteForm(topic, source.get('actor'), source.get('source_link'), request.POST), arguments=ArgumentFormSet(request.POST), ) if form.is_valid(): services.create_quote(request.user, topic, **form.cleaned_data) return redirect(topic) else: form = forms.CombinedForms( source=forms.SourceForm(), quote=forms.QuoteForm(topic, actor=None, source_link=None), arguments=ArgumentFormSet(), ) return render(request, 'manopozicija/quote_form.html', { 'topic': topic, 'source_form': form['source'], 'quote_form': form['quote'], 'arguments_formset': form['arguments'], })
def get_formset(self): if not self._formset: post_data = None post_files = None if self.request.method == 'POST': posted_listing_id = self.request.POST.get('listing_id', '') if posted_listing_id == self.id: post_data = self.request.POST post_files = self.request.FILES fields = { c.name : c.create_hidden_form_field() for c in self.selected_hidden_columns } fields.update({ c.name : c.create_form_field() for c in self.can_edit_columns }) form_class = type('ListingRowForm{}'.format(self.suffix), (self.listing_row_form_base_class,), {'base_fields': fields}) formset_class = forms.formset_factory(form_class, extra=0) self._formset = formset_class(post_data, post_files, initial=self.get_formset_initial_values(), prefix='{}{}'.format(LISTING_FORMSET_PREFIX, self.suffix) ) for form in self._formset: form.listing = self form.form_name = 'row_form' return self._formset
def cart(request): """It showes customer's cart and allows to change products numbers. """ cart = Cart(request) products = cart.get() products_ids = {p.id: p for p in products} OrderFormSet = formset_factory(OrderForm, extra=0) if request.method == 'POST': formset = OrderFormSet(request.POST) if formset.is_valid() and formset.has_changed(): for cd in formset.cleaned_data: product = get_object_or_404(Product, pk=cd['product']) cart.add_or_update(product, cd['count']) else: data = [{'product': p.id, 'count': c} for p, c in products.items()] formset = OrderFormSet(initial=data) for form in formset: form.product_info = products_ids[int(form.hidden_fields()[0].value())] context = { 'products': products, 'formset': formset, 'cart_count': cart.count(), 'total': cart.total(), } return cart.set(render(request, 'sales/cart.html', context))
def get(self, request, *args, **kwargs): tutoria = models.Tutoria.objects.get(pk=self.kwargs['pk']) EncuentroTutoriaFormSet = formset_factory(EncuentroTutoriaForTutoriaForm) formset = EncuentroTutoriaFormSet() return render(request, self.template_name, {'object': tutoria, 'formset': formset } )
def permissions(request, title): document = get_object_or_404(Document, url_title=title) content_type = ContentType.objects.get_for_model(document) check_permissions(document, request.user, [document.edit_permission_name]) if not document.show_permissions_editor(): raise PermissionDenied() PermissionForm = get_permission_form(document) PermissionFormset = formset_factory(get_permission_form(document), extra=0) initial_data = PermissionForm.prepare_initial_data(Group.objects.all(), content_type, document) formset = PermissionFormset(request.POST or None, initial=initial_data) if request.POST and formset.is_valid(): for form in formset: form.save(document) messages.success(request, _("Permissions have been changed successfully.")) if request.user.has_perm(document.edit_permission_name, document): return HttpResponseRedirect(reverse(document.get_permissions_url_name(), args=[document.url_title])) if request.user.has_perm(document.view_permission_name, document): return HttpResponseRedirect(reverse(document.get_view_url_name(), args=[document.url_title])) return HttpResponseRedirect(reverse('index')) return render(request, 'documents_permissions.html', { 'document': document, 'formset_header': PermissionForm.header(content_type), 'formset': formset, 'active_page': 'permissions', 'permission_overview': document_permission_overview(request.user, document), })
def createIRI(request): RegisteredIRIFormset = formset_factory(RegisteredIRIForm, formset=RequiredFormSet) # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: formset = RegisteredIRIFormset(request.POST) # check whether it's valid: if formset.is_valid(): # process the data in form.cleaned_data as required for form in formset: if form.is_valid(): vocabulary_path = form.cleaned_data['vocabulary_path'] termType = form.cleaned_data['term_type'] term = form.cleaned_data['term'] profile = UserProfile.objects.get(user=request.user) iriobj = RegisteredIRI.objects.create(vocabulary_path=vocabulary_path, term_type=termType, term=term, userprofile=profile) return render(request, 'iriCreationResults.html', {'newiri': iriobj.return_address()}) # # vocab = Vocabulary.objects.create # termType = form.cleaned_data['termType'] # term = form.cleaned_data['term'] # # profile = UserProfile.objects.get(user=request.user) # iriobj = RegisteredIRI.objects.create(vocab=vocabulary, term_type=termType, term=term, userprofile=profile) # return HttpResponseRedirect(reverse('iriCreationResults')) # # redirect to a new URL: # if a GET (or any other method) we'll create a blank form else: formset = RegisteredIRIFormset() return render(request, 'createIRI.html', {'formset': formset})
def attendEvents(request): """ Attend events view. Basically a formset that allows users to tick attendance. That's all there is to it, really. """ context_dict = {} event_list = Event.objects.all().order_by('startDate') EventFormSet = formset_factory(EventCheckbox, extra=len(event_list)) count = 0 if request.method == 'POST': # have we been given a few events to attend? Good! formset = EventFormSet(request.POST) for form in formset: # if event X is checked, make sure we're attending. If not, make sure we're not attending. if form.is_valid() and form.cleaned_data == {}: EventAttendance.objects.filter(event=event_list[count], user=request.user).delete() else: EventAttendance.objects.get_or_create(event=event_list[count], user=request.user) count += 1 return HttpResponseRedirect(reverse('userProfile')) formset = EventFormSet() eventsWithAttendance = [] for event in event_list: # tick the relevant boxes in the formset to make sure the starting data is consistent checked = EventAttendance.objects.filter(event=event, user=request.user).exists() if checked: checked = "checked" else: checked = "" eventsWithAttendance += [{'event': event, 'checked': checked}] context_dict = {'eventswithattendance': eventsWithAttendance, 'formset': formset} return render(request, 'stove/attendEvents.html', context_dict)
def edit(request, title, new_autosaved_pages=None, initial=None): document = Document.objects.get(url_title=title) content_type = ContentType.objects.get_for_model(document) check_permissions(document, request.user, [document.edit_permission_name]) # if the edit form has a formset we will initialize it here formset_factory = document.Form.get_formset_factory() formset = formset_factory(request.POST or None, instance=document) if formset_factory is not None else None if formset is not None: template_name = "{app}_edit.html".format(app=content_type.app_label) else: template_name = "documents_edit.html" success, form = handle_edit(request, document, formset, initial) __, attachment_form, __ = handle_attachment(request, document) if success: messages.success(request, _("Successfully saved changes")) return HttpResponseRedirect(reverse('documents:view', args=[document.url_title])) else: return render(request, template_name, { 'document': document, 'form': form, 'attachment_form': attachment_form, 'active_page': 'edit', 'creation': (len(revisions.get_for_object(document)) == 0), 'new_autosaved_pages': new_autosaved_pages, 'permission_warning': permission_warning(request.user, content_type, document), 'supported_image_types': settings.SUPPORTED_IMAGE_TYPES, 'formset': formset, })
def memberregister(request,num,num1): # ,initial={'batch': profile.batch} profile = sellerprofile.objects.get(id = num1) print profile.batch memberFormSet = formset_factory(memberProfileForm, extra=int(num)) member_form = memberFormSet(request.POST or None) # for i in range(int(num)) # , extra=int(num) # initial=[{'batch': profile.batch}] # member_form = memberFormSet(initial=[{'batch': profile.batch} for i in range(int(num))]) title = "Add Members" context = { 'memberform':member_form, 'title':title } if member_form.is_valid(): # p = sellerprofile.objects.filter(batch = profile.batch) for form in member_form: member = form.save(commit=False) member.group = profile member.save() messages.success(request, 'Profile details updated.') title = "Your Response Has been Recorded" return HttpResponseRedirect('/login/') # return render(request,"memberregister.html",{'messages':messages}) return render(request,"memberregister.html",context)
def nuevaCotizacionView(request, idComparativa): class RequiredFormSet(BaseFormSet): def __init__(self, *args, **kwargs): super(RequiredFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False comparativa = Comparativa.objects.get(pk=idComparativa) tipo = comparativa.tipoSeguro.nombre.idSeguro formset = formset_factory(forms.CoberturaUtilizadaForm, max_num=20, formset=RequiredFormSet) cuformset = formset() for form in cuformset.forms: form.fields['idCobertura'].queryset = Cobertura.objects.filter(seguro__pk=tipo) coberturaUtilizadaForm = forms.CoberturaUtilizadaForm() coberturaUtilizadaForm.fields['idCobertura'].queryset = Cobertura.objects.filter(seguro__pk=tipo) context = { 'comparativa': Comparativa.objects.get(pk=idComparativa), 'aseguradoras': Aseguradora.objects.all(), 'cotizacionForm': forms.CotizacionForm(), 'coberturaUtilizadaForm': coberturaUtilizadaForm, 'coberturas': Cobertura.objects.filter(seguro__pk=tipo), 'formset': cuformset, 'uploadFileForm': forms.UploadFileForm(), } return render(request, 'schema/nuevaCotizacion.html', context)
def get_context_data(self, **kwargs): context = super(PlanDetailView, self).get_context_data(**kwargs) ConnectionFormSet = formset_factory(ConnectionForm, extra=0) context['formset'] = ConnectionFormSet() context['empty_plan'] = False if self.object.connection_set.all().count() else True context['other_plans'] = Plan.objects.filter(experiment=self.object.experiment).exclude(pk=self.object.pk) return context
def encuesta_crear_view(request): url = reverse('vista_encuesta_crear') message = '' if request.session.get('_info_message'): message = request.session.get('_info_message') request.session['_info_message'] = '' encuesta_form = EncuestaAddForm() OpcionFormset = formset_factory(OpcionAddForm, extra=2, max_num=5, validate_min=True) opcion_formset = OpcionFormset(prefix='opcion') if request.method == "POST": encuesta_form = EncuestaAddForm(request.POST) opcion_formset = OpcionFormset(request.POST, prefix='opcion') if encuesta_form.is_valid() and opcion_formset.is_valid(): encuesta = encuesta_form.save(commit=False) encuesta.usuario_crea = request.user encuesta.save() for form in opcion_formset.forms: preguntas = form.save(commit=False) preguntas.encuesta = encuesta preguntas.votos_total = 0 preguntas.save() request.session['_info_message'] = 'Encuesta agregada correctamente' return HttpResponseRedirect(url) context = { 'opcion_formset': opcion_formset, 'encuesta_form' : encuesta_form, 'message': message } return render(request, 'encuestas/encuesta_crear.html',context)
def update(request, application_id=None): application = mdl.application.find_by_id(application_id) past_attachments = list_attachments(application) UploadDocumentFileFormSet = formset_factory(UploadDocumentFileForm, extra=0) document_formset = UploadDocumentFileFormSet() applicant = mdl.applicant.find_by_user(request.user) remove_attachment_form = RemoveAttachmentForm() list_choices = [x[1] for x in document_type.DOCUMENT_TYPE_CHOICES] data = { "tab_active": navigation.ATTACHMENTS_TAB, "application": application, "applications": mdl.application.find_by_user(request.user), "document_formset": document_formset, "attachments": past_attachments, "removeAttachmentForm": remove_attachment_form, "list_choices": list_choices } data.update(demande_validation.get_validation_status(application, applicant)) letter_motivation_doc_present = False curriculum_doc_present = False if application.application_type == application_type.ADMISSION: for p in past_attachments: if p.description == 'letter_motivation': letter_motivation_doc_present=True if p.description == 'curriculum': curriculum_doc_present=True data.update({'letter_motivation_doc_present': letter_motivation_doc_present, 'curriculum_doc_present': curriculum_doc_present}) return render(request, "admission_home.html", data)
def renew (modeladmin, request, queryset): count = len(queryset) RenewalFormSet = formset_factory(RenewForm, min_num=count, max_num=count) if request.method == 'POST': # create a form instance and populate with data from request: # generate 1st of present month, last day of month next year today = local_date_now() term_start = today.replace(day=1) next_year = today.year + 1 last_day_of_month = end_of_month(next_year, today.month) term_end = datetime.date(next_year, today.month, last_day_of_month) # sort by name members = sort_members_by_name(queryset) # generate formset initial = [] for member in queryset: if today < member.date_end: term_start = member.date_end term_end = member.date_end.replace(year=member.date_end.year + 1) term_start_future = True else: term_start_future = False data = {} data['old_start' ] = member.date_start data['old_end' ] = member.date_end data['new_start' ] = term_start data['new_end' ] = term_end data['future' ] = term_start_future data['first_name'] = member.first_name data['last_name' ] = member.last_name data['email' ] = member.email data['id' ] = member.pk initial.append(data) formset = RenewalFormSet(initial=initial) return render(request, 'membership/renew.html', {'formset': formset})
def lettre_create(request): formset = None if request.method == 'POST': form = LettreForm(request.POST or None) formset = LigneForm(request.POST or None) ArticleFormSet = formset_factory(LigneForm, extra=2) formset = ArticleFormSet(initial=[{'test': 'Django is now open source', }, {'test': 'Django is now open source2', }]) else: form = LettreForm() if form.is_valid(): data = form.cleaned_data location = data['location'] locataires = location.locataires data.update({'dateJour': timezone.now()}) data = get_personne_detail(data, locataires, location) data = get_batiment_detail(location.batiment, data) data = get_gestionnaire_detail(data) data.update({'tableau': [['ligne1', 'ligne2'], ['ligne1', 'ligne2']]}) filename = fill_template( 'documents/lettre.odt', data, output_format='pdf') return FileResponse(filename, 'lettre.{}'.format('pdf')) else: return render(request, 'documents/lettre.html', {'form': form})
def lettre_indexation(request, contrat_location_id): modele = mdl.modele_document.find_by_reference('LETTRE_INDEXATION') a_contrat_location = mdl.contrat_location.find_by_id(contrat_location_id) doctype = request.POST.get('format_fichier', 'pdf') ArticleFormSet = formset_factory(LigneForm, extra=2) formset = ArticleFormSet(initial=[{'test': 'Django is now open source', }, {'test': 'Django is now open source2', }]) data = _build_data(formset) locataires = a_contrat_location.locataires locataire = locataires.first() if locataire: personne = locataire.personne data.update({'titre': _get_civilite(locataire.civilite)}) if personne: data.update({NOM_KEY: personne.nom}) data.update({PRENOM_KEY: personne.prenom}) data.update({"sujet": "Lettre d'indexation"}) data = _batiment_detail(a_contrat_location.batiment, data) data = _gestionnaire_detail(data) filename = fill_template( "documents/{}".format(modele.fichier_modele), data, output_format=doctype) return FileResponse(filename, 'LETTRE_INDEXATION.{}'.format(doctype))
def manage_filesystem(request): user = request.user # necessary for the @user_passes_test decorator if request.is_ajax(): if request.method == 'POST': datasets_chosen = [] compression_chosen = [] new_filesystem_formset = formset_factory(ManageFileSystems, extra=NUMBER_OF_FORMS_IN_FORMSET) for form_num in range(NUMBER_OF_FORMS_IN_FORMSET): datasets_chosen.append([request.POST.get('form-{}-datasets'.format(form_num)), request.POST.get('form-{}-datasets'.format(form_num))]) compression_chosen.append([request.POST.get('form-{}-compression'.format(form_num)), ('form-{}-compression'.format(form_num))]) formset = new_filesystem_formset(request.POST, form_kwargs={'dataset_choices': datasets_chosen, 'compression_choice': compression_chosen}) if formset.is_valid(): if not formset.cleaned_data[0]['edit_mode']: # only send 1st form - edit mode only uses 1 instance of formset, rest are obsolete create_task = async(engineering.create_filesystems, data=formset.cleaned_data) else: create_task = async(engineering.edit_filesystems, data=formset.cleaned_data[0]) if create_task: return HttpResponse(str(create_task)) else: return HttpResponseServerError else: error_str = '' for e in formset.errors: for k, v in e.items(): logger.error(k + '>>>' + v) er_str = '' for er in v: er_str += '{}, '.format(er) error_str += '{}, '.format(er_str.strip(', ')) return HttpResponse('ERROR: ' + error_str.strip(', ')) return HttpResponseServerError
def menu_item_edit(request, menu_item_pk): menu_item = get_object_or_404(MenuItem, pk=menu_item_pk) if not menu_item.can_edit(request.user): raise PermissionDenied if request.user.is_superuser: form = MenuItemAdminForm(request.POST or None, instance=menu_item) else: form = MenuItemForm(request.POST or None, instance=menu_item) PermissionForm = get_permission_form(menu_item) PermissionFormset = formset_factory(get_permission_form(menu_item), extra=0) content_type = ContentType.objects.get_for_model(menu_item) initial_data = PermissionForm.prepare_initial_data(Group.objects.all(), content_type, menu_item) formset = PermissionFormset(request.POST or None, initial=initial_data) if form.is_valid() and request.POST and formset.is_valid(): form.save() for permission_form in formset: permission_form.save(menu_item) messages.success(request, _("Successfully edited menu item.")) return redirect('menu_items_index') return render(request, 'menu_item_edit.html', { 'form': form, 'formset_header': PermissionForm.header(content_type), 'formset': formset, })
def new(request): game_form = GameForm(request.user) screenshot_form = formset_factory(ScreenshotForm, extra=4, min_num=4, max_num=8) if request.method == "POST": game_form = GameForm(request.user, request.POST, request.FILES) screenshot_form = screenshot_form(request.POST, request.FILES) if game_form.is_valid(): game = game_form.save() if screenshot_form.is_valid(): for scf in screenshot_form: action = scf.save(commit=False) if not action.image: continue action.game = game action.save() messages.add_message(request, messages.SUCCESS, "New game has been added successfully.") return redirect(reverse('games_index')) else: game.delete() messages.add_message(request, messages.ERROR, "Add new game failed. Check your screenshots.") else: messages.add_message(request, messages.ERROR, "Add new game failed. Check your game data.") data = {'game_form': game_form, 'screenshot_form': screenshot_form} return render(request, 'games/new.html', data)
def construct_GeneEntryFormSet(user, media, *args, **kwargs): alleles = media.type.allele_set.all() class GeneEntryForm(forms.Form): allele = forms.ModelChoiceField( alleles, widget=forms.HiddenInput(), required=False, ) value = forms.IntegerField( required=False, max_value=settings.MAX_VALUE, min_value=settings.MIN_VALUE, help_text="1-5" ) GeneEntryFormSet = forms.formset_factory(GeneEntryForm, extra=0) initial = [ { 'allele': allele.id, 'value': get_genentry_value_or_none(user, media, allele), } for allele in alleles ] formset = GeneEntryFormSet( *args, initial=initial, **kwargs ) return formset
def new(request): company_form = CompanyForm() developer_form = formset_factory(DeveloperForm, min_num=1) if request.method == "POST": company_form = CompanyForm(request.POST, request.FILES) developer_form = developer_form(request.POST, request.FILES) if company_form.is_valid(): company = company_form.save(commit=False) company.user = request.user company.save() if developer_form.is_valid(): for dev in developer_form: action = dev.save(commit=False) action.company = company action.save() messages.add_message(request, messages.SUCCESS, "New company with its team memebers have been saved successfully.") return redirect(reverse('companies_index')) else: company.delete() messages.add_message(request, messages.ERROR, "Team memebers saving failed. Check yout data.") else: messages.add_message(request, messages.ERROR, "Add new company failed. Check yout data.") data = {'company_form': company_form, 'developer_form': developer_form} return render(request, 'companies/new.html', data)
def lettre_indexation_form(request, contrat_location_id): modele = mdl.modele_document.find_by_reference('LETTRE_INDEXATION') form = None formset = None contrat_location = None if request.method == 'POST': pass else: if contrat_location_id: contrat_location = mdl.contrat_location.find_by_id(contrat_location_id) ArticleFormSet = formset_factory(LigneForm, extra=2) formset = None # formset = ArticleFormSet(initial=[{'test': 'Django is now open source', }, # {'test': 'Django is now open source2', }]) # form = LettreForm(initial={'sujet': modele.sujet, 'format': "docx", 'fichier_modele': modele.fichier_modele, 'titre': 'Monsieur', 'tableSet': formset}) # form = LettreForm(request.POST or None) return render(request, "documents/lettre.html", {'form': form, 'formset': formset, 'contrat_location': contrat_location, 'modele': modele})
def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) slug = self.kwargs.get('slug', '') goals = get_object_or_404(Goals, slug = slug) MyGoalsFormset = formset_factory(MyGoalsForm, extra = 0) my_goals_formset = MyGoalsFormset(initial = [{'item': x.id, 'value': x.ref_value} for x in goals.item_goal.all()]) self.log_action = "view" self.log_context['category_id'] = goals.topic.subject.category.id self.log_context['category_name'] = goals.topic.subject.category.name self.log_context['category_slug'] = goals.topic.subject.category.slug self.log_context['subject_id'] = goals.topic.subject.id self.log_context['subject_name'] = goals.topic.subject.name self.log_context['subject_slug'] = goals.topic.subject.slug self.log_context['topic_id'] = goals.topic.id self.log_context['topic_name'] = goals.topic.name self.log_context['topic_slug'] = goals.topic.slug self.log_context['goals_id'] = goals.id self.log_context['goals_name'] = goals.name self.log_context['goals_slug'] = goals.slug self.log_context['timestamp_start'] = str(int(time.time())) super(SubmitView, self).createLog(self.request.user, self.log_component, self.log_action, self.log_resource, self.log_context) self.request.session['log_id'] = Log.objects.latest('id').id self.log_context = {} return self.render_to_response(self.get_context_data(my_goals_formset = my_goals_formset))
def epi12a(request): formset = formset_factory(StudentForm12A, extra=request.session["students"]) if request.method == "POST": formset = formset(request.POST, request.FILES) r = getreport(request, "create") f = getfacility(request, r) for form in formset: if form.is_valid(): id = f.district_id * 10000000000 id += f.pk * 1000000 id += f.count f.count += 1 f.save() s = Student(id=id) s.fname = form.cleaned_data["fname"] s.mname = form.cleaned_data["mname"] s.lname = form.cleaned_data["lname"] s.dateofbirth = form.cleaned_data["dateofbirth"] s.age = calc_age(form.cleaned_data["dateofbirth"]) s.entry_date = form.cleaned_data["entrydate"] s.noshotrecord = form.cleaned_data["noshotrecord"] s.exempt_rel = form.cleaned_data["exempt_rel"] s.exempt_med = form.cleaned_data["exempt_med"] s.dtap1 = form.cleaned_data["dtap1"] s.dtap2 = form.cleaned_data["dtap2"] s.dtap3 = form.cleaned_data["dtap3"] s.dtap4 = form.cleaned_data["dtap4"] s.polio1 = form.cleaned_data["polio1"] s.polio2 = form.cleaned_data["polio2"] s.polio3 = form.cleaned_data["polio3"] s.hib = form.cleaned_data["hib"] s.hepb1 = form.cleaned_data["hepb1"] s.hepb2 = form.cleaned_data["hepb2"] s.hepb3 = form.cleaned_data["hepb3"] s.mmr1 = form.cleaned_data["mmr1"] s.varicella1 = form.cleaned_data["varicella1"] s.pe = form.cleaned_data["pe"] s.tb = form.cleaned_data["tb"] s.notes = form.cleaned_data["notes"] s.facility_id = f.pk if s.dtap1: s.dtap2 = s.dtap1 if s.dtap2: s.dtap3 = s.dtap2 if s.dtap3: s.dtap4 = s.dtap3 if s.polio1: s.polio2 = s.polio1 if s.polio2: s.polio3 = s.polio2 if s.hepb1: s.hepb2 = s.hepb1 if s.hepb2: s.hepb3 = s.hepb2 s.save() s.report.add(r) return HttpResponseRedirect(reverse("reportinput:complete")) else: formset = formset() return render(request, "reportinput/epi12a.html", {"formset": formset})
def multi_permissions(request): """ 批量操作权限(添加、修改) :param request: :return: """ # 获取用户操作的类型(批量添加 or 批量修改) post_type = request.GET.get('type') generate_formset_class = formset_factory(MultiAddPermissionForm, extra=0) update_formset_class = formset_factory(MultiEditPermissionForm, extra=0) # 错误信息标志位 has_generate_error = False has_update_error = False # 增:批量添加权限 if request.method == 'POST' and post_type == 'generate': formset = generate_formset_class(data=request.POST) if formset.is_valid(): object_list = [] # formset中没有错误信息,则将用户提交的数据获取到 post_row_list = formset.cleaned_data for i in range(0, formset.total_form_count()): row_dict = post_row_list[i] try: new_object = models.Permission(**row_dict) # 唯一校验:检查当前对象在数据库是否存在 new_object.validate_unique() object_list.append(new_object) except Exception as e: formset.errors[i].update(e) generate_formset_error = formset has_generate_error = True if not has_generate_error: # 获取所有数据后,再统一添加到数据库 models.Permission.objects.bulk_create(object_list, batch_size=100) else: generate_formset_error = formset has_generate_error = True # 改:批量修改权限 if request.method == 'POST' and post_type == 'update': formset = update_formset_class(data=request.POST) if formset.is_valid(): post_row_list = formset.cleaned_data for i in range(0, formset.total_form_count()): row_dict = post_row_list[i] # 指定当前修改的权限id permission_id = row_dict.pop('id') try: row_object = models.Permission.objects.filter( id=permission_id).first() # 通过反射批量更新row_object对象的属性值 for k, v in row_dict.items(): setattr(row_object, k, v) # 唯一校验通过,直接保存到数据库 row_object.validate_unique() row_object.save() except Exception as e: formset.errors[i].update(e) update_formset_error = formset has_update_error = True else: update_formset_error = formset has_update_error = True reload_session(request) # 查: # 1. 获取项目中所有的URL all_url_dict = get_all_url_dict() router_name_set = set(all_url_dict.keys()) # 2 获取数据库中所有的URL permissions = models.Permission.objects.all().values( 'id', 'title', 'name', 'url', 'menu_id', 'pid_id') permission_dict = OrderedDict() permission_name_set = set() for row in permissions: permission_dict[row['name']] = row permission_name_set.add(row['name']) # 3 项目url和数据库url比较 for name, value in permission_dict.items(): router_row_dict = all_url_dict.get(name) if not router_row_dict: continue if value['url'] != router_row_dict['url']: value['url'] = '路由和数据库中不一致' # 3.1 计算出应该增加的name generate_name_list = router_name_set - permission_name_set generate_formset = generate_formset_class(initial=[ row_dict for name, row_dict in all_url_dict.items() if name in generate_name_list ]) # 3.2 计算出应该删除的name delete_name_list = permission_name_set - router_name_set delete_row_list = [ row_dict for name, row_dict in permission_dict.items() if name in delete_name_list ] # 3.3 计算出应该更新的name update_name_list = permission_name_set & router_name_set update_formset = update_formset_class(initial=[ row_dict for name, row_dict in permission_dict.items() if name in update_name_list ]) # 判断是否有错误信息 generate_formset = generate_formset_error if has_generate_error else generate_formset update_formset = update_formset_error if has_update_error else update_formset return render( request, 'rbac/multi_permissions.html', { 'generate_formset': generate_formset, 'delete_row_list': delete_row_list, 'update_formset': update_formset, })
def rfq_material_editor(request, code): menu_texts = FrontendTexts('menu') instructions = Instructions('rfqs', 'edit') try: backend_host = MachineConfigurator().getBackend() r = requests.post(backend_host + '/auth/rfqs/' + code) backend_message = BackendMessage(json.loads(r.text)) backend_result = json.loads(backend_message.getValue()) material_data = backend_result['materialList'] rfq_form = RFQFormOnlyinfo(initial=backend_result) MaterialFormSet = formset_factory(ExtMaterialForm, extra=0) materials_formset = MaterialFormSet(initial=material_data) if request.method == 'POST': rfq_form = RFQFormOnlyinfo(request.POST) materials_formset = MaterialFormSet(request.POST) if rfq_form.is_valid() and materials_formset.is_valid(): # ... update current material with the data provided # ... send data to backend creator = RFQCreator() result = creator.editRFQwithMaterials(rfq_form, materials_formset, material_data) result_json = [] for rfq in result: result_json.append(json.dumps(rfq)) r = requests.put(backend_host + '/auth/rfqs/' + code, json=result) backend_message = BackendMessage(json.loads(r.text)) backend_result = json.loads(backend_message.getValue()) return render(request, 'rfqs/rfq_material_editor.html', {'menu_text': menu_texts.getComponent(), 'view_texts': view_texts.getComponent(), 'updated_materials': backend_result}) return render(request, 'rfqs/rfq_material_editor.html', {'menu_text': menu_texts.getComponent(), 'view_texts': view_texts.getComponent(), 'rfq_form': rfq_form, 'materials_formset': materials_formset, 'instructions_title': instructions.getTitle(), 'instructions_steps': instructions.getSteps()}) except ValueError as exception: print("There is a problem with the backend return value") print(exception) return render(request, 'rfqs/rfq_material_editor.html', {'menu_text': menu_texts.getComponent(), 'view_texts': view_texts.getComponent(), 'error_message': 'No such RFQ exists in the DB: ' + code, 'instructions_title': instructions.getTitle(), 'instructions_steps': instructions.getSteps()}) except ConnectionError as exception: print("Backend connection problem") print(exception) return render(request, 'rfqs/rfq_material_editor.html', {'menu_text': menu_texts.getComponent(), 'view_texts': view_texts.getComponent(), 'error_message': 'Backend connection problem', 'instructions_title': instructions.getTitle(), 'instructions_steps': instructions.getSteps()}) except Exception as exception: print(exception) return render(request, 'rfqs/rfq_material_editor.html', {'menu_text': menu_texts.getComponent(), 'view_texts': view_texts.getComponent(), 'error_message': 'System error', 'instructions_title': instructions.getTitle(), 'instructions_steps': instructions.getSteps()})
def multi_permissions(request): """ 批量操作权限 :param request: :return: """ post_type = request.GET.get('type') # 更新、编辑 FormSet = modelformset_factory(models.Permission, MultiPermissionForm, extra=0) # 增加 AddFormSet = formset_factory(MultiPermissionForm, extra=0) # 数据库所有URL permissions = models.Permission.objects.all() # 项目路由系统的所有URL router_dict = get_all_url_dict(ignore_namespace_list=[ 'admin', ]) # 数据库所有权限别名 permissions_name_set = set([i.url_name for i in permissions]) # 项目路由系统的所有权限别名 router_name_set = set(router_dict.keys()) # 新增的url别名信息 add_name_set = router_name_set - permissions_name_set add_formset = AddFormSet(initial=[ row for name, row in router_dict.items() if name in add_name_set ]) # 更新的url别名信息 update_name_set = permissions_name_set & router_name_set update_formset = FormSet(queryset=models.Permission.objects.filter( url_name__in=update_name_set)) # 删除的url别名信息 del_name_set = permissions_name_set - router_name_set del_formset = FormSet(queryset=models.Permission.objects.filter( url_name__in=del_name_set)) # 批量添加 if request.method == 'POST' and post_type == 'add': add_formset = AddFormSet(request.POST) if add_formset.is_valid(): permission_obj_list = [ models.Permission(**i) for i in add_formset.cleaned_data ] query_list = models.Permission.objects.bulk_create( permission_obj_list) for i in query_list: permissions_name_set.add(i.url_name) # 批量更新 if request.method == 'POST' and post_type == 'update': update_formset = FormSet(request.POST) if update_formset.is_valid(): update_formset = FormSet(queryset=models.Permission.objects.filter( url_name__in=update_name_set)) return render( request, 'multi_permissions.html', { 'del_formset': del_formset, 'update_formset': update_formset, 'add_formset': add_formset, })
def post(self, request, *args, **kwargs): if request.is_ajax(): if EliminarFabricacionForm.nombre_form in request.POST: form = EliminarFabricacionForm(request.POST or None) if form.is_valid(): form.delete() return HttpResponse('Fabricación eliminada') return HttpResponse('No se pudo eliminar la fabricación') else: context = {'forms': [], 'titulo_form': 'crear fabricación'} form = FabricacionForm(request.POST or None) forms = [] cantidad_produccion = request.POST.get('cantidad_produccion') if cantidad_produccion: almacen_id = request.POST.get('almacen_produccion') producto_id = request.POST.get('producto') subforms_initials = { campo: valor for campo, valor in request.POST.items() if campo.startswith('componente_') } producto = Producto.objects.actuales().get(id=producto_id) almacen = Almacen.objects.actuales().get(id=almacen_id) for componente_id, cantidad_componente in producto.componentes_totales( Q(producto_componente__seguimiento__isnull=False) ).items(): componente = Producto.objects.get(id=componente_id) prefix = 'componente_' + str(componente_id) totalForms = subforms_initials.get(prefix + '-' + 'TOTAL_FORMS') initial = [] if totalForms: for i in range(int(totalForms)): subformPrefix = prefix + '-' + str(i) + '-' subformInitial = { key.replace(subformPrefix, ''): value for key, value in subforms_initials.items() if subformPrefix in key } initial.append(subformInitial) opciones_totales = almacen.codigos_lotes_producto( componente) seleccionados = [] for subform_initial in initial: seleccionados.append( subform_initial['codigo_lote']) opciones = [ opcion for opcion in opciones_totales if opcion[0] not in seleccionados ] getcontext().prec = 4 cantidad_componente = cantidad_componente * Decimal( cantidad_produccion) FabricacionLoteFormset = formset_factory( form=FabricacionLoteForm, extra=0, max_num=len(opciones_totales), can_delete=False, formset=FabricacionLoteBaseFormSet) formset = FabricacionLoteFormset( request.POST, prefix='componente_' + str(componente_id), form_kwargs={ 'almacen': almacen, 'componente': componente, 'cantidad_componente': cantidad_componente, 'opciones': opciones }, initial=initial) forms.append(formset) if form.is_valid(): valido = True for formset in forms: if not formset.is_valid(): valido = False if valido: fabricacion = form.save() for formset in forms: formset.save(fabricacion) context['forms'].append(FabricacionForm()) context['success'] = self.created_message return render(request, self.template_name, context) context['forms'].append(form) for form in forms: context['forms'].append(form) return render(request, self.template_name, context) raise Http404
def submit_view(request, class_pk, assignment_pk): class_object = get_object_or_404(models.Class, pk=class_pk) if request.user not in class_object.students.all( ) and request.user not in class_object.instructors.all(): raise Http404('No Class matches the given query.') assignment_object = get_object_or_404(models.Assignment, pk=assignment_pk) if not assignment_object in class_object.assignments.all( ) or not assignment_object.submittable(request.user): raise Http404('No Assignment matches the given query.') files = None length = 0 if assignment_object.submission_files: files = [ file.text for file in assignment_object.submission_files.files.all() ] length = len(files) SubmitFormSetFactory = formset_factory(form=forms.SubmitForm, formset=forms.SubmitFormSet, min_num=length, validate_min=True, max_num=length, validate_max=True) if request.method == 'POST': formset = SubmitFormSetFactory(request.POST, request.FILES, filenames=files) if formset.is_valid(): submission_object = models.Submission() submission_object.enrolled_class = class_object submission_object.assignment = assignment_object submission_object.submitter = request.user submission_object.save() for form in formset: if form.is_valid(): file_object = form.save(commit=False) file_object.creator = request.user upload_to = file_object.file.field.upload_to file_object.file.field.upload_to = lambda instance, filename: 'submission/{pk}/{name}'.format( pk=submission_object.pk, name=form.fields['file'].label) file_object = form.save() file_object.file.field.upload_to = upload_to submission_object.files.add(file_object) submission_object.save() trigger_run(submission_object) return redirect('submission', submission_pk=submission_object.pk) else: context = { 'formset': formset, 'class': class_object, 'assignment': assignment_object } return render(request, 'codemark/submit.html', context=context) else: formset = SubmitFormSetFactory(filenames=files) context = { 'formset': formset, 'class': class_object, 'assignment': assignment_object } return render(request, 'codemark/submit.html', context=context)
class Meta: model = Book fields = ('name', ) labels = { 'name': 'Book Name' } widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Book Name here' } ) } BookFormset = formset_factory(BookForm) BookModelFormset = modelformset_factory( Book, fields=('name', ), extra=1, widgets={ 'name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Book Name here' } ) } ) AuthorFormset = modelformset_factory( Author,
from django import forms from django.forms import formset_factory from django.contrib.admin import widgets import os from .models import Student CHOICE = { ("0", "在室"), ("1", "教室"), ("2", "校内"), ("3", "自宅"), } class RadioForm(forms.ModelForm): class Meta: model = Student fields = ("place", ) widgets = { "place": forms.RadioSelect, } RadioFormSet = formset_factory(RadioForm, extra=2)
def __init__(self): self.template = 'md_form_structure_edit.html' self.field_formset_object = formset_factory(FieldEntityForm, extra=1, max_num=1)
class Meta: model = Dataset fields = ('name', 'description') class NewModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.name class FormTag(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': _("Name")}), label=False, required=True) type = forms.ChoiceField(choices=PRIMITIVES_CHOICES, label=False, required=True) color = forms.CharField(widget=forms.TextInput(attrs={'type': 'color'}), required=True, label=False) TagFormset = formset_factory(FormTag, extra=1) class FormExperiment(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(), label=_("Name")) description = forms.CharField(widget=forms.Textarea(attrs={'placeholder': _("1024 characters maximum"), "rows": 3}), label=_("Description")) dataset = NewModelChoiceField(queryset=Dataset.objects.all(), label=_("Dataset")) team = NewModelChoiceField(queryset=Team.objects.all(), label=_("Team")) class Meta: model = Experiment fields = ('name', 'description', 'dataset', 'team')
VEHICLE_TYPES = (('0', 'Vehicle'), ('1', 'Vehicle (concession)'), ('2', 'Motorcycle')) class VehicleInfoForm(forms.Form): vehicle_rego = forms.CharField( label="Vehicle Registration", widget=forms.TextInput(attrs={'required': True})) vehicle_type = forms.ChoiceField(label="Vehicle Type", choices=VEHICLE_TYPES) entry_fee = forms.BooleanField(required=False, label="Entry fee") VehicleInfoFormset = forms.formset_factory(VehicleInfoForm, extra=1, max_num=8) class MakeBookingsForm(forms.Form): num_adult = forms.IntegerField(min_value=0, max_value=16, label="Adults (non-concessions)") num_child = forms.IntegerField(min_value=0, max_value=16, label="Children (ages 6-15)") num_concession = forms.IntegerField(min_value=0, max_value=16, label="Concessions") num_infant = forms.IntegerField(min_value=0, max_value=16, label="Infants (ages 0-5)")
if self.cleaned_data['amount'] != 0: # new budget models.Budget.objects.create( category_id=self.cleaned_data['category_id'], month=self.cleaned_data['month'], amount=self.cleaned_data['amount']) elif self.cleaned_data['amount'] != 0: models.Budget.objects.update_or_create( id=self.cleaned_data['budget_id'], defaults={'amount': self.cleaned_data['amount']}) else: models.Budget.objects.get( id=self.cleaned_data['budget_id']).delete() BudgetFormSet = forms.formset_factory(BudgetForm, extra=0) class TransactionForm(forms.ModelForm): class Meta: model = models.Transaction fields = [ 'title', 'source_account', 'destination_account', 'amount', 'date', 'value_date', 'category', 'notes' ] amount = forms.DecimalField(max_digits=10, decimal_places=2, min_value=0.01) category = forms.ModelChoiceField(queryset=models.Category.objects.exclude( active=False).order_by('name'),
def create_questions_answers(request, pk): """ The view for teachers to create their questions and answers to them. :param request: :param pk: primary key of the test :return: """ try: test = Test.objects.get(pk=pk) questions = Question.objects.filter(test=test) except ObjectDoesNotExist: messages.info(request, "There is no test with this id") test = None questions = [] answer_form_set = formset_factory(form=AnswerForm, extra=1, can_delete=False) if request.method == "POST": question_form = QuestionForm(request.POST) answer_forms = answer_form_set(request.POST) if question_form.is_valid(): valid = True question = question_form.save() valid_answers = [] one_correct = False for answer_form in answer_forms: if answer_form.is_valid(): if not answer_form.cleaned_data: messages.warning(request, "One of the answer forms is not valid") return render(request, 'teachers/questions-answers-creation.html', {'question_form': QuestionForm, 'answer_formset': answer_form_set, 'test': test, 'questions': questions }) if answer_form.cleaned_data["is_correct"]: one_correct = True answer_form = answer_form.save(commit=False) answer_form.question = question valid_answers.append(answer_form) else: valid = False if one_correct: if valid: # only if everything is valid and there is one correct answer -> save for answer_form in valid_answers: answer_form.save() test_current = Test.objects.get(pk=pk) question.test.add(test_current) messages.info(request, "Question {} created".format(len(questions))) else: messages.warning(request, "One of the forms is not valid") else: messages.warning(request, "At least one answer must be correct") return render(request, 'teachers/questions-answers-creation.html', {'question_form': QuestionForm, 'answer_formset': answer_form_set, 'test': test, 'questions': questions })
def signup(request): UserEducationFormset = formset_factory(UserEducationForm) # Helpful variables error = None educations = [] formsAmountLen = 0 formsAmount = 0 emptyformsAmount = 0 educFormsError = False if request.method == 'POST': user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) usereducation_formset = UserEducationFormset(request.POST) formsAmountLen = len(usereducation_formset) # Do the validation to force cleaned_data attributes be created usereducation_formset.is_valid() # Check out whether forms are empty for education in usereducation_formset: field_university = education.cleaned_data.get('university') field_degree = education.cleaned_data.get('degree') field_educ_start = education.cleaned_data.get('educ_start') field_educ_end = education.cleaned_data.get('educ_end') field_programme = education.cleaned_data.get('programme') formsAmount += 1 if not field_university and not field_degree and not field_educ_start and not field_educ_end and not field_programme: emptyformsAmount += 1 if formsAmount == 1 and emptyformsAmount == 1: error = 'Ваша форма пуста' educFormsError = True if formsAmount > 0 and emptyformsAmount > 0 and formsAmount != emptyformsAmount: error = 'Одна из ваших форм полностью пуста' educFormsError = True if formsAmount > 1 and formsAmount == emptyformsAmount: error = 'Все ваши формы пусты' educFormsError = True if user_form.is_valid() and profile_form.is_valid( ) and usereducation_formset.is_valid() and not educFormsError: user = user_form.save(commit=False) user.is_active = False user.save() day = profile_form.cleaned_data.get('day_of_birth') month = profile_form.cleaned_data.get('month_of_birth') year = profile_form.cleaned_data.get('year_of_birth') user.profile.patronymic = profile_form.cleaned_data.get( 'patronymic') user.profile.birth_date = '%s-%s-%s' % (year, month, day) user.profile.save() educations = [] for education in usereducation_formset: educations.append( UserEducation( user=user, university=education.cleaned_data.get('university'), degree=education.cleaned_data.get('degree'), educ_start=education.cleaned_data.get('educ_start'), educ_end=education.cleaned_data.get('educ_end'), programme=education.cleaned_data.get('programme'), )) try: with transaction.atomic(): UserEducation.objects.bulk_create(educations) except IntegrityError: # If the transaction failed return HttpResponse( 'An error occured while creating your profile') current_site = get_current_site(request) mail_subject = 'Activate your account' message = render_to_string( 'acc_activate_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes( user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = user_form.cleaned_data.get('email') email = EmailMessage(mail_subject, message, to=[to_email]) email.send() # Redirect to a beautiful page is preferred return render(request, 'after_signup.html') else: user_form = UserForm() profile_form = ProfileForm() usereducation_formset = UserEducationFormset() return render( request, 'signup.html', { 'user_form': user_form, 'profile_form': profile_form, 'usereducation_formset': usereducation_formset, 'error': error, 'emptyformsAmount': emptyformsAmount, 'formsAmount': formsAmount, 'formsAmountLen': formsAmountLen })
type = forms.ChoiceField(choices=EGG_TYPE_CHOICES, required=False) fakeYmd = forms.DateField(required=False, widget=forms.DateInput(attrs={'type': 'date'})) productCode = forms.CharField(widget=forms.HiddenInput(), required=False) locationSale = forms.ChoiceField(widget=Select2Widget, choices=Location.objects.none) in_location = forms.CharField(max_length=255, widget=forms.HiddenInput(), required=False) def __init__(self, *args, **kwargs): super(EggForm, self).__init__(*args, **kwargs) self.fields['location'] = forms.ChoiceField( widget=Select2Widget, choices=[('', '')] + list( Location.objects.values_list('code', 'codeName').filter( type='03').filter(delete_state='N').order_by('code'))) self.fields['locationSale'] = forms.ChoiceField( widget=Select2Widget, required=False, choices=[('', '')] + list( Location.objects.values_list('code', 'codeName').filter( type='07').filter(delete_state='N').order_by('code'))) self.fields['product'] = forms.ChoiceField( widget=Select2Widget, choices=[('', '')] + list(EggCode.objects.values_list('code', 'codeName'))) EggFormSet = formset_factory(EggForm)
class OrderCreateRefundView(UpdateView): model = Order template_name = "shuup/admin/orders/create_refund.jinja" context_object_name = "order" form_class = forms.formset_factory(RefundForm, extra=1) def get_queryset(self): shop_ids = Shop.objects.get_for_user(self.request.user).values_list("id", flat=True) return Order.objects.exclude(deleted=True).filter(shop_id__in=shop_ids) def get_context_data(self, **kwargs): context = super(OrderCreateRefundView, self).get_context_data(**kwargs) context["title"] = _("Create Refund -- %s") % context["order"] context["toolbar"] = Toolbar([ PostActionButton( icon="fa fa-check-circle", form_id="create_refund", text=_("Create Refund"), extra_css_class="btn-success", ) ], view=self) # Allowing full refunds for suppliers would block the refunds for # rest of the suppliers since full refund can only be created once supplier = context["supplier"] = get_supplier(self.request) if not supplier: context["toolbar"].append( URLActionButton( url=reverse("shuup_admin:order.create-full-refund", kwargs={"pk": self.object.pk}), icon="fa fa-dollar", text=_("Refund Entire Order"), extra_css_class="btn-info", disable_reason=_("This order already has existing refunds") if self.object.has_refunds() else None ) ) # Setting the line_numbers choices dynamically creates issues with the blank formset, # So adding that to the context to be rendered manually context["line_number_choices"] = self._get_line_number_choices(supplier) lines = lines = self.object.lines.all() if supplier: lines = lines.filter(supplier=supplier) context["json_line_data"] = { line.ordering: self._get_line_data(self.object, line) for line in lines } return context def _get_line_data(self, order, line): shop = order.shop total_price = line.taxful_price.value if shop.prices_include_tax else line.taxless_price.value base_data = { "id": line.id, "type": "other" if line.quantity else "text", "text": line.text, "quantity": line.quantity - line.refunded_quantity, "sku": line.sku, "baseUnitPrice": line.base_unit_price.value, "unitPrice": total_price / line.quantity if line.quantity else 0, "unitPriceIncludesTax": shop.prices_include_tax, "amount": line.max_refundable_amount.value, "errors": "", "step": "" } if line.product: shop_product = line.product.get_shop_instance(shop) supplier = line.supplier stock_status = supplier.get_stock_status(line.product.pk) if supplier else None base_data.update({ "type": "product", "product": { "id": line.product.pk, "text": line.product.name }, "step": shop_product.purchase_multiple, "logicalCount": stock_status.logical_count if stock_status else 0, "physicalCount": stock_status.physical_count if stock_status else 0, "salesDecimals": line.product.sales_unit.decimals if line.product.sales_unit else 0, "salesUnit": line.product.sales_unit.symbol if line.product.sales_unit else "" }) return base_data def get_form_kwargs(self): kwargs = super(OrderCreateRefundView, self).get_form_kwargs() kwargs.pop("instance") return kwargs def _get_line_text(self, line): text = "line %s: %s" % (line.ordering + 1, line.text) if line.sku: text += " (SKU %s)" % (line.sku) return text def _get_line_number_choices(self, supplier): lines = self.object.lines.all() if supplier: lines = lines.filter(supplier=supplier) line_number_choices = [("", "---")] if settings.SHUUP_ALLOW_ARBITRARY_REFUNDS and self.object.get_total_unrefunded_amount(supplier).value > 0: line_number_choices += [("amount", _("Refund arbitrary amount"))] return line_number_choices + [ (line.ordering, self._get_line_text(line)) for line in lines if ( ( (line.type == OrderLineType.PRODUCT and line.max_refundable_quantity > 0) or ( line.type != OrderLineType.PRODUCT and line.max_refundable_amount.value > 0 and line.max_refundable_quantity > 0 ) ) and line.type != OrderLineType.REFUND ) ] def get_form(self, form_class=None): formset = super(OrderCreateRefundView, self).get_form(form_class) # Line orderings are zero-indexed, but shouldn't display that way choices = self._get_line_number_choices(get_supplier(self.request)) for form in formset.forms: form.fields["line_number"].choices = choices formset.empty_form.fields["line_number"].choices = choices return formset def _get_refund_line_info(self, order, data, supplier): refund_line_info = {} amount_value = data.get("amount", 0) or 0 line_number = data.get("line_number") quantity = data.get("quantity", 0) or 1 restock_products = data.get("restock_products") if line_number != "amount": lines = order.lines.filter(ordering=line_number) if supplier: lines = lines.filter(supplier=supplier) line = lines.first() if not line: return None refund_line_info["line"] = line refund_line_info["quantity"] = quantity refund_line_info["restock_products"] = bool(restock_products) else: refund_line_info["line"] = "amount" refund_line_info["text"] = data.get("text") refund_line_info["quantity"] = 1 refund_line_info["amount"] = Money(amount_value, order.currency) return refund_line_info def form_valid(self, form): order = self.object supplier = get_supplier(self.request) refund_lines = [] for refund in form.cleaned_data: line = self._get_refund_line_info(order, refund, supplier) if line: refund_lines.append(line) try: order.create_refund(refund_lines, created_by=self.request.user, supplier=supplier) except RefundExceedsAmountException: messages.error(self.request, _("Refund amount exceeds order amount.")) return self.form_invalid(form) except InvalidRefundAmountException: messages.error(self.request, _("Refund amounts should match sign on parent line.")) return self.form_invalid(form) messages.success(self.request, _("Refund created.")) return HttpResponseRedirect(get_model_url(order))
def myprofile_edit(request): user = request.user first_name = user.first_name last_name = user.last_name UserEducationFormset = formset_factory(form=UserEducationForm, extra=0) educations = UserEducation.objects.all().filter(user=user).values() educationsNum = len(educations) educFormsError = False birth = user.profile.birth_date day_of_birth = birth.strftime('%d') month_of_birth = birth.strftime('%m') year_of_birth = birth.strftime('%Y') formsAmount = 0 emptyformsAmount = 0 if request.method == 'POST': userform = UserFormEdit(instance=user, data=request.POST) profileform = ProfileForm(instance=user.profile, data=request.POST) usereducs_formset = UserEducationFormset(request.POST) # Do the validation to force cleaned_data attributes be created usereducs_formset.is_valid() # Check out whether forms are empty for education in usereducs_formset: field_university = education.cleaned_data.get('university') field_degree = education.cleaned_data.get('degree') field_educ_start = education.cleaned_data.get('educ_start') field_educ_end = education.cleaned_data.get('educ_end') field_programme = education.cleaned_data.get('programme') formsAmount += 1 if not field_university and not field_degree and not field_educ_start and not field_educ_end and not field_programme: emptyformsAmount += 1 if formsAmount == 1 and emptyformsAmount == 1: error = 'Ваша форма пуста' educFormsError = True if formsAmount > 0 and emptyformsAmount > 0 and formsAmount != emptyformsAmount: error = 'Одна из ваших форм полностью пуста' educFormsError = True if formsAmount > 1 and formsAmount == emptyformsAmount: error = 'Все ваши формы пусты' educFormsError = True if userform.is_valid() and profileform.is_valid( ) and usereducs_formset.is_valid() and not educFormsError: validated = True user = userform.save(commit=False) user.save() day = profileform.cleaned_data.get('day_of_birth') month = profileform.cleaned_data.get('month_of_birth') year = profileform.cleaned_data.get('year_of_birth') educations = [] for education in usereducs_formset: educations.append( UserEducation( user=user, university=education.cleaned_data.get('university'), degree=education.cleaned_data.get('degree'), educ_start=education.cleaned_data.get('educ_start'), educ_end=education.cleaned_data.get('educ_end'), programme=education.cleaned_data.get('programme'), )) try: with transaction.atomic(): UserEducation.objects.all().filter(user=user).delete() UserEducation.objects.bulk_create(educations) except IntegrityError: # If the transaction failed return HttpResponse( 'An error occured while creating your profile') return redirect('myprofile') else: userform = UserFormEdit(instance=user) profileform = ProfileForm(instance=user.profile, initial={ 'day_of_birth': day_of_birth, 'month_of_birth': month_of_birth, 'year_of_birth': year_of_birth }) usereducs_formset = UserEducationFormset(initial=educations) return render( request, 'myprofile_edit.html', { 'userform': userform, 'profileform': profileform, 'usereducs_formset': usereducs_formset, 'educationsNum': educationsNum, 'emptyformsAmount': emptyformsAmount, 'formsAmount': formsAmount })
quantity=form['quantity']) class ItemForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.use_required_attribute = True product = ProductChoiceField(queryset=models.Product.objects.all()) quantity = forms.IntegerField(max_value=250, min_value=1) use_required_attribute = True ItemFormSet = forms.formset_factory(form=ItemForm, extra=0, min_num=1, max_num=10, validate_max=True, validate_min=True) ItemFormSet.clean = clean ItemFormSet.save = save class AddressForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, label_suffix='', **kwargs) self.fields['customer'].widget = forms.HiddenInput() if self.instance.id: self.fields['street'].widget = forms.HiddenInput() self.fields['postal_code'].widget = forms.HiddenInput() self.fields['city'].widget = forms.HiddenInput()
class Meta: model = PurchaseBill fields = ['supplier'] class PurchaseItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['stock'].widget.attrs.update({'class': 'textinput form-control setprice', 'required': 'true'}) self.fields['quantity'].widget.attrs.update({'class': 'textinput form-control setquantity', 'required': 'true'}) self.fields['price'].widget.attrs.update({'class': 'textinput form-control putprice', 'required': 'true', 'readonly': 'true'}) class Meta: model = PurchaseItem fields = ['stock', 'quantity', 'price'] PurchaseItemFormset = formset_factory(PurchaseItemForm, extra=1) class SupplierForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'class': 'textinput form-control'}) self.fields['phone'].widget.attrs.update({'class': 'textinput form-control', 'maxlength': '10'}) self.fields['email'].widget.attrs.update({'class': 'textinput form-control'}) class Meta: model = Supplier fields = ['name', 'phone', 'email'] class SaleForm(forms.ModelForm):
name = forms.CharField( required=False, widget=forms.HiddenInput(attrs={"readonly": "readonly"})) class ReviewSinglePersonForm(ReviewSinglePersonNameOnlyForm): source = forms.CharField( required=False, widget=forms.HiddenInput(attrs={"readonly": "readonly"})) party_description = forms.CharField(required=False, widget=forms.HiddenInput()) BulkAddFormSet = forms.formset_factory( QuickAddSinglePersonForm, extra=15, formset=BaseBulkAddFormSet, can_delete=True, ) BulkAddReviewNameOnlyFormSet = forms.formset_factory( ReviewSinglePersonNameOnlyForm, extra=0, formset=BaseBulkAddReviewFormSet) BulkAddReviewFormSet = forms.formset_factory(ReviewSinglePersonForm, extra=0, formset=BaseBulkAddReviewFormSet) class SelectAnythingChoiceField(forms.ChoiceField): """ Because we don't always show all parties on the initial page load (we leave JavaScript to add the non-current parties sometimes), we need to
def api_test(request, projectId, apiId, envId): username = request.session.get('user', '') # 根据session中的user获得登陆的用户名 project_obj = project.objects.get(id=projectId) #根据projectId 查询项目数据 保存在project_obj中 api_obj = apiList.objects.get(id=apiId) #根据apiid 查询api数据 保存在api_obj中 api_params = ApiParams.objects.filter(apiId=apiId) api_bodys = ApiBody.objects.filter(apiId=apiId) obj_test = ApiTest.objects.filter(apiId=apiId, env_id=envId).values() params_len = len(api_params) bodys_len = len(api_bodys) expect_key = ExpectKey(initial={'apiId': api_obj}) expect_key_type = ExpectKey_Type(initial={'apiId': api_obj}) result_len = 12 ScriptForm = Script() env_obj = env.objects.filter(projectId=projectId) if obj_test: MyFormSet = formset_factory(Case, formset=ORDER_FIXED, can_order=True, can_delete=True, extra=0) formset = MyFormSet(initial=obj_test, form_kwargs={"initial": {'apiId': apiId, 'is_empty': False, 'envId': envId}}) else: MyFormSet = formset_factory(Case, formset=ORDER_FIXED, can_order=True, can_delete=True) formset = MyFormSet(initial=obj_test, form_kwargs={"initial": {'apiId': apiId, 'is_empty': True}}) script_modelformsets = modelformset_factory(ApiScript, form=Base_script, fields=("ScriptName", "ScriptTpye", "createTime", "updateTime", "author"), extra=0, can_order=True, can_delete=True) script_modelformset = script_modelformsets(queryset=ApiScript.objects.filter(apiId=apiId)) if request.method == "POST": expectkey_POST = ExpectKey(request.POST, initial={'apiId': api_obj}) case_formet_POST_SAVE = MyFormSet(request.POST, form_kwargs={"initial": {'apiId': apiId, 'is_empty': False, 'envId': envId}}) expectkey_type_POST = ExpectKey_Type(request.POST, initial={'apiId': api_obj}) if "testcasesave" in request.POST: if case_formet_POST_SAVE.is_valid() and expectkey_POST.is_valid() and expectkey_type_POST.is_valid(): temp = case_formet_POST_SAVE.cleaned_data temp_result_key = expectkey_POST.cleaned_data temp_result_key_type = expectkey_type_POST.cleaned_data del temp_result_key['response_code'] del temp_result_key['response_time'] del temp_result_key_type['codetype'] del temp_result_key_type['timetype'] try: case_formet_POST_SAVE.save(datas=temp, apiId=api_obj, result_key=temp_result_key, result_key_type=temp_result_key_type, env_id=envId, api_bodys=api_bodys, api_params=api_params) new_obj_test = ApiTest.objects.filter(apiId=apiId, env_id=envId).values() case_handle.create_case(projectId=projectId, apiId=apiId, case_num=len(new_obj_test), project_name=project_obj.name, api_name=api_obj.apiName, env_id=envId) except: messages.flash(request, "报错", "保存测试用例出错", level="error") return HttpResponseRedirect("/api/project%s/api%s/test/%s" % (projectId, apiId, envId)) elif "exec" in request.POST: if case_formet_POST_SAVE.is_valid() and expectkey_POST.is_valid() and expectkey_type_POST.is_valid(): temp = case_formet_POST_SAVE.cleaned_data temp_result_key = expectkey_POST.cleaned_data temp_result_key_type = expectkey_type_POST.cleaned_data del temp_result_key['response_code'] del temp_result_key['response_time'] del temp_result_key_type['codetype'] del temp_result_key_type['timetype'] try: case_formet_POST_SAVE.save(datas=temp, apiId=api_obj, result_key=temp_result_key, result_key_type=temp_result_key_type, env_id=envId, api_bodys=api_bodys, api_params=api_params) new_obj_test = ApiTest.objects.filter(apiId=apiId, env_id=envId).values() case_handle.create_case(projectId=projectId, apiId=apiId, case_num=len(new_obj_test), project_name=project_obj.name, api_name=api_obj.apiName, env_id=envId) except: messages.flash(request, "报错", "保存测试用例出错", level="error") # pytest.main(['/Users/smzdm/luna/platform3/api/testcase/%s/%s/%s' % (project_obj.pk, api_obj.pk, envId)]) # 'python3 -m unittest discover -s /Users/smzdm/luna/platform3/api/testcase/1/1/5/ -p "case*_test.py"' # path = "'/Users/smzdm/luna/platform3/api/testcase/%s/%s/%s'" % (project_obj.pk, api_obj.pk, envId) # file_list = os.listdir(path) # TestSuit = unittest.TestSuite # discover = unittest.defaultTestLoader.discover("/Users/smzdm/luna/platform3/api/testcase/1/1/5/", # pattern="case*_test.py") # runner = unittest.TextTestRunner() # runner.run(discover) # os.system("pytest /Users/smzdm/luna/platform3/api/testcase/%s/%s/%s" % (project_obj.pk, api_obj.pk, envId)) public_handle.os_run(projectId=project_obj.pk, apiId=api_obj.pk, envId=envId) return HttpResponseRedirect("/api/project%s/api%s/test/%s" % (projectId, apiId, envId)) elif "script" in request.POST: script_POST = Script(request.POST, request.FILES) if script_POST.is_valid(): temp = script_POST.cleaned_data script_obj = ApiScript.objects.get_or_create(apiId=api_obj, ScriptTpye=temp['ScriptTpye'], ScriptName=temp['ScriptFile']) if script_obj[1]: print("success") script_obj[0].ScriptFile = temp['ScriptFile'] script_obj[0].author = username script_obj[0].save() else: print("failed") script_obj[0].ScriptFile = temp['ScriptFile'] script_obj[0].author = username script_obj[0].updateTime = datetime.datetime.now() script_obj[0].save() script_handle.save_script(work_path=os.getcwd(), apiId=apiId, filename=temp['ScriptFile']) return HttpResponseRedirect("/api/project%s/api%s/test/%s" % (projectId, apiId, envId)) elif "script_delete" in request.POST: script_modelformset_POST = script_modelformsets(request.POST) if script_modelformset_POST.is_valid(): exist_file_list = [] script_modelformset_POST.save() script_query = ApiScript.objects.filter(apiId=api_obj) for script in script_query: exist_file_list.append(script.ScriptName) script_handle.del_script(work_path=os.getcwd(), apiId=apiId, exist_file_list=exist_file_list) return HttpResponseRedirect("/api/project%s/api%s/test/%s" % (projectId, apiId, envId)) else: return HttpResponseRedirect("/api/project%s/api%s/test/%s" % (projectId, apiId, envId)) else: ctx = {'username': username, 'project_obj': project_obj, 'api_obj': api_obj, 'api_params': api_params, 'params_len': params_len, 'api_bodys': api_bodys, 'bodys_len': bodys_len, 'expect_key': expect_key, 'result_len': result_len, 'formset': formset, 'expect_key_type': expect_key_type, 'ScriptForm': ScriptForm, 'script_modelformset': script_modelformset, 'env_default': int(envId), 'env_obj': env_obj, } return render(request, 'apitest.html', ctx)
def new_thread(request, subject_id): subject = get_object_or_404(Subject, pk=subject_id) poll_subject_formset = formset_factory(PollSubjectForm, extra=3) if request.method == "POST": thread_form = ThreadForm(request.POST) post_form = PostForm(request.POST) poll_form = PollForm(request.POST) poll_subject_formset = poll_subject_formset(request.POST) if thread_form.is_valid() and post_form.is_valid(): if request.POST.get('is_a_poll', None) and poll_form.is_valid( ) and poll_subject_formset.is_valid(): thread = thread_form.save(False) thread.subject = subject thread.user = request.user thread.save() post = post_form.save(False) post.user = request.user post.thread = thread post.save() poll = poll_form.save(False) poll.thread = thread poll.save() for subject_form in poll_subject_formset: subject = subject_form.save(False) subject.poll = poll subject.save() messages.success(request, "You have created a new thread with a poll!") return redirect(reverse('thread', args={thread.pk})) else: thread = thread_form.save(False) thread.subject = subject thread.user = request.user thread.save() post = post_form.save(False) post.user = request.user post.thread = thread post.save() messages.success(request, "You have created a new thread!") return redirect(reverse('thread', args={thread.pk})) else: thread_form = ThreadForm() post_form = PostForm(request.POST) poll_form = PollForm() poll_subject_formset = poll_subject_formset() args = { 'thread_form': thread_form, 'post_form': post_form, 'subject': subject, 'poll_form': poll_form, 'poll_subject_formset': poll_subject_formset } args.update(csrf(request)) return render(request, 'forum/thread_form.html', args)
def post(self, request, *args, **kwargs): if request.is_ajax(): forms = [] form = FabricacionForm(initial=dict(request.POST.items())) forms.append(form) getcontext().prec = 4 cantidad_produccion = request.POST.get('cantidad_produccion') if cantidad_produccion: almacen_id = request.POST.get('almacen_produccion') changed_data = request.POST.get('changed_data') agregar_componente = '' if not changed_data: producto_id = request.POST.get('producto') subforms_initials = { campo: valor for campo, valor in request.POST.items() if campo.startswith('componente_') } elif changed_data != 'almacen_produccion': producto_id = request.POST.get('producto') if changed_data != 'producto': subforms_initials = { campo: valor for campo, valor in request.POST.items() if campo.startswith('componente_') } if changed_data.endswith('añadir'): agregar_componente = changed_data.split('-')[0] else: subforms_initials = [] else: producto_id = None subforms_initials = [] if almacen_id and producto_id: producto = Producto.objects.actuales().get(id=producto_id) almacen = Almacen.objects.actuales().get(id=almacen_id) if subforms_initials: for componente_id, cantidad_componente in producto.componentes_totales( Q(producto_componente__seguimiento__isnull=False )).items(): componente = Producto.objects.get(id=componente_id) prefix = 'componente_' + str(componente_id) totalForms = subforms_initials.get(prefix + '-' + 'TOTAL_FORMS') initial = [] if totalForms: for i in range(int(totalForms)): subformPrefix = prefix + '-' + str(i) + '-' subformInitial = { key.replace(subformPrefix, ''): value for key, value in subforms_initials.items() if subformPrefix in key } initial.append(subformInitial) opciones_totales = almacen.codigos_lotes_producto( componente) seleccionados = [] for subform_initial in initial: seleccionados.append( subform_initial['codigo_lote']) opciones = [ opcion for opcion in opciones_totales if opcion[0] not in seleccionados ] if agregar_componente == prefix: initial.append( {'codigo_lote': opciones.pop(0)[0]}) cantidad_componente = cantidad_componente * Decimal( cantidad_produccion) FabricacionLoteFormset = formset_factory( form=FabricacionLoteForm, extra=0, max_num=len(opciones_totales), can_delete=False, formset=FabricacionLoteBaseFormSet) formset = FabricacionLoteFormset( prefix='componente_' + str(componente_id), form_kwargs={ 'almacen': almacen, 'componente': componente, 'cantidad_componente': cantidad_componente, 'opciones': opciones }, initial=initial) forms.append(formset) else: for componente_id, cantidad_componente in producto.componentes_totales( Q(producto_componente__seguimiento__isnull=False )).items(): componente = Producto.objects.get(id=componente_id) opciones = almacen.codigos_lotes_producto( componente) cantidad_componente = cantidad_componente * Decimal( cantidad_produccion) FabricacionLoteFormset = formset_factory( form=FabricacionLoteForm, extra=1, max_num=len(opciones), can_delete=False, formset=FabricacionLoteBaseFormSet) formset = FabricacionLoteFormset( prefix='componente_' + str(componente_id), form_kwargs={ 'almacen': almacen, 'componente': componente, 'cantidad_componente': cantidad_componente, 'opciones': opciones }) forms.append(formset) return render(request, 'forms.html', { 'forms': forms, 'titulo_form': 'crear fabricación' }) raise Http404
profiles = [] creator = Profile.objects.get(id=self.user.id) for form in self.forms: profile = form.cleaned_data.get('profile') if profile in profiles: raise ValidationError('There are same users in the set') if creator == profile: raise ValidationError( 'Do not enter creator as a member! It will be added automatically\n' 'Current logged in user is treated as a party creator') profiles.append(profile) PartyMemberFormSet = formset_factory(MemberForm, formset=BasePartyMemberFormSet, validate_max=True) class CreatePartyFromExistingForm(forms.ModelForm): class Meta: model = Party fields = ('name', ) form_name = 'create_party_from_existing_form' name = forms.CharField( max_length=1024, label='Party name', widget=widgets.TextInput( attrs={'placeholder': 'Enter here your party name'}))
label=_('CategoryOptionComboID'), required=True) comment = forms.CharField(label=_('DHIS2 Comment'), required=False) def append_to(self, datavalue_maps): if self.cleaned_data: datavalue_maps.append( DataValueMap( column=self.cleaned_data['column'], data_element_id=self.cleaned_data['data_element_id'], category_option_combo_id=self. cleaned_data['category_option_combo_id'], comment=self.cleaned_data['comment'], )) DataValueMapFormSet = forms.formset_factory(DataValueMapForm, extra=2) class DataValueMapFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super(DataValueMapFormSetHelper, self).__init__(*args, **kwargs) self.form_method = 'post' self.form_class = 'form-horizontal' self.label_class = 'col-sm-3 col-md-2' self.field_class = 'col-sm-9 col-md-8 col-lg-6' self.layout = crispy.Layout( crispy.Fieldset( _('DataValue map'), crispy.Field('column'), crispy.Field('data_element_id'),
def multi_permissions(request): """ 批量操作权限 :param request: :return: """ post_type = request.GET.get('type') MultiPermissionFormSet = formset_factory(MultiPermissionForm, extra=0) generate_formset = None update_formset = None if request.method == 'POST' and post_type == 'generate': formset = MultiPermissionFormSet(request.POST) if not formset.is_valid(): generate_formset = formset else: for row_dict in formset.cleaned_data: row_dict.pop('id') models.Permission.objects.create(**row_dict) if request.method == 'POST' and post_type == 'update': formset = MultiPermissionFormSet(request.POST) if formset.is_valid(): for row_dict in formset.cleaned_data: permission_id = row_dict.pop('id') models.Permission.objects.filter(id=permission_id).update( **row_dict) else: update_formset = formset # 1.1 去数据库中获取所有权限 # [{},{}] permissions = models.Permission.objects.all().values( 'id', 'title', 'url', 'name', 'menu_id', 'pid_id') # {'rbac:menu_list':{},'rbac:menu_add':{..}} permisssion_dict = OrderedDict() for per in permissions: permisssion_dict[per['name']] = per # 1.2 数据库中有的所有权限name的集合 permission_name_set = set(permisssion_dict.keys()) # 2.1 获取路由系统中所有的URL # {'rbac:menu_list':{'url':.... },,,} router_dict = get_all_url_dict(ignore_namespace_list=['admin']) for row in permissions: name = row['name'] if name in router_dict: router_dict[name].update(row) # 2.2 路由系统中的所有权限name的集合 router_name_set = set(router_dict.keys()) # 需要新建:数据库无、路由有 if not generate_formset: generate_name_list = router_name_set - permission_name_set generate_formset = MultiPermissionFormSet(initial=[ row for name, row in router_dict.items() if name in generate_name_list ]) # 需要删除:数据库有、路由无 destroy_name_list = permission_name_set - router_name_set destroy_formset = MultiPermissionFormSet(initial=[ row for name, row in permisssion_dict.items() if name in destroy_name_list ]) # 需要更新:数据库有、路由有 if not update_formset: update_name_list = permission_name_set.intersection(router_name_set) update_formset = MultiPermissionFormSet(initial=[ row for name, row in router_dict.items() if name in update_name_list ]) return render( request, 'rbac/multi_permissions.html', { 'destroy_formset': destroy_formset, 'update_formset': update_formset, 'generate_formset': generate_formset, })
GroupPagePermission.objects.bulk_create([ GroupPagePermission(group=self.instance, page=page, permission_type=permission_type) for (page, permission_type) in permissions_to_add ]) def as_admin_panel(self): return render_to_string( 'wagtailusers/groups/includes/page_permissions_formset.html', {'formset': self}) GroupPagePermissionFormSet = forms.formset_factory( PagePermissionsForm, formset=BaseGroupPagePermissionFormSet, extra=0, can_delete=True) class NotificationPreferencesForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) user_perms = UserPagePermissionsProxy(self.instance.user) if not user_perms.can_publish_pages(): del self.fields['submitted_notifications'] if not user_perms.can_edit_pages(): del self.fields['approved_notifications'] del self.fields['rejected_notifications'] class Meta:
]) raise forms.ValidationError( "Error, total bid amount cannot exceed donation amount." ) if form.cleaned_data['bid'] in bids: form.errors['__all__'] = form.error_class([ "Error, cannot bid more than once for the same bid in the same donation." ]) raise forms.ValidationError( "Error, cannot bid more than once for the same bid in the same donation." ) bids.add(form.cleaned_data['bid']) DonationBidFormSet = formset_factory(DonationBidForm, formset=DonationBidFormSetBase, max_num=DonationBidFormSetBase.max_bids) class PrizeTicketForm(forms.Form): prize = forms.fields.IntegerField( label="", required=False, widget=tracker.widgets.MegaFilterWidget(model="prize")) amount = forms.DecimalField( decimal_places=2, max_digits=20, required=False, validators=[positive, nonzero], widget=tracker.widgets.NumberInput(attrs={ 'class': 'cprizeamount',
def createNewMovie(request): GenreFormSet = formset_factory(AddGenreForm, formset=BaseAddGenreFormset) is_genre_error = False ActorFormSet = formset_factory(AddActorForm, formset=BaseAddActorForm) is_actor_error = False if request.method == 'POST': form1 = CreateMovieForm(request.POST, request.FILES) genreforms = GenreFormSet(request.POST, prefix='genre') actorforms = ActorFormSet(request.POST, prefix='actor') if form1.is_valid(): if genreforms.is_valid(): if actorforms.is_valid(): wizard = VFMovieTool(); input_movie_name = form1.cleaned_data['movie_name'] input_year = form1.cleaned_data['year'] input_director = form1.cleaned_data['director'] input_poster_cover = form1.cleaned_data['movie_poster'] input_director = wizard.formatPersonName(input_director) genre_list = [] for form in genreforms: if form.cleaned_data: temp_genre = form.cleaned_data['genre'] if temp_genre not in genre_list: genre_list.append(temp_genre) actor_list = [] for form in actorforms: if form.cleaned_data: actor_list.append(form.cleaned_data['actor_name']) print("\t",actor_list) print("\t",genre_list) print("\t",input_movie_name) print("\t",input_year) print("\t",input_director) try: direct = Director.objects.get(director_name = input_director ) except Director.DoesNotExist: direct = Director(director_name = input_director) direct.save() newMovie = Movie(movie_name = input_movie_name, year = input_year, director = direct, movie_poster = input_poster_cover, movie_by = request.user) newMovie.save() for genre in genre_list: newGenre = Movie_Genre(movie = newMovie, genre = genre) newGenre.save() for people in actor_list: peopled = wizard.formatPersonName(people) try: newActor = Actor.objects.get(actor_name = peopled ) except Actor.DoesNotExist: newActor = Actor(actor_name = peopled) newActor.save() newMovieActor = Movie_Actor(movie = newMovie, actor = newActor) newMovieActor.save() return redirect('movies:movie_detail',newMovie.id) else: is_actor_error = True else: is_genre_error = True actorforms= ActorFormSet(prefix='actor') genreforms = GenreFormSet(prefix='genre') form1 = CreateMovieForm() return render(request, 'movies/createMovie.html',{'form1':form1,'genreforms':genreforms,'is_genre_error':is_genre_error,'actorforms':actorforms,'is_actor_error':is_actor_error})
def _question_formset(self, request): QuestionFormSet = formset_factory(forms.QuestionForm) question_formset = QuestionFormSet(request.POST, prefix='questions') return question_formset
def add_patient(request): report_id = request.session.get("reviewing_report", None) if not report_id: return redirect("patients:report-queue") report = get_object_or_404(Report, pk=report_id) patient = Patient.from_report(report) sourcelines = report.source.strip().split("\n") SourceFormset = formset_factory(SourceForm, extra=len(sourcelines) - 1) if request.method == "POST": form = PatientForm(request.POST) sformset = SourceFormset(request.POST) if form.is_valid() and sformset.is_valid(): if "submit" in request.POST: patient = form.save() report.report_state = report.CONVERTED report.save() messages.success( request, "A new patient has been added. Thank you for the contribution.", ) elif "mark_verified" in request.POST: report.report_state = report.VERIFIED report.save() messages.info( request, "The report has been marked as verfied. " "One of the admins will review it shortly. Thank you for " "verifying the report.", ) for sform in sformset: if sform.is_valid() and sform.has_changed(): source = Source( url=sform.cleaned_data["url"], description=sform.cleaned_data["description"], patient=patient) source.save() del request.session["reviewing_report"] return redirect("patients:report-queue") else: form = PatientForm(instance=patient) initials = [] for line in sourcelines: if line.strip().startswith("http"): initials.append({"url": line.strip(), "description": ""}) else: initials.append({"url": line.strip(), "description": ""}) sformset = SourceFormset(initial=initials) return render( request, "patients/add_patient.html", { "patient": patient, "form": form, "sformset": sformset, "report_id": report_id }, )