def post(self, req): form = ReportForm(req.POST) # Verifica validacao if form.is_valid(): dados_form = form.data report = Report.objects.create(condition=dados_form['condition'], name=dados_form['name'], command=dados_form['command']) report.save() # Valores para tabela na pagina principal commands = Command.objects.all() computers = Computer.objects.all() return render( req, 'pagina_principal.html', { "computers": computers, "commands": commands, "event": 1, "msg": "Report editado com sucesso." }) return render(req, self.template_name, {'form': form})
def new_report(request): if request.method == 'POST': reportform = ReportForm(request.POST) if reportform.is_valid(): report = reportform.save() report.created_by = request.user report.save() action.send(request.user, verb='created lot number', action_object=report, target=report) return HttpResponseRedirect(report.get_absolute_url()) else: copy = request.GET.get('copy', None) if copy: report = Report.objects.get(lot_number=copy) reportform = ReportForm(instance=report) else: reportform = ReportForm( initial={'receiving_date': time.strftime("%Y-%m-%d")}) return render_to_response('reports/new_report.html', { 'reportform': reportform, }, context_instance=RequestContext(request))
def report(request): if request.method == "POST": form = ReportForm(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.save() return redirect(reverse("reportdone")) else: form = ReportForm() return render(request, 'reports/report.html', {'form': form})
def view_reports(request): formset = ReportForm() if request.method == 'POST': if request.POST.get('report'): report = get_object_or_404(Report, pk=request.POST.get('report')) form = ReportForm(request.POST, instance=report) if form.is_valid(): report = form.save() report.save() return render_to_response('reports/reports.html',{ 'success': "success", 'form': formset, 'reports': Report.objects.all()}, context_instance=RequestContext(request)) else: return render_to_response('reports/reports.html',{ 'error': form.errors, 'form': formset, 'reports': Report.objects.all()}, context_instance=RequestContext(request)) else: form = ReportForm(request.POST) if form.is_valid(): new_report= form.save() return render_to_response('reports/reports.html',{ 'success': "success", 'form': formset, 'reports': Report.objects.all()}, context_instance=RequestContext(request)) else: return render_to_response('reports/reports.html',{ 'error': form.errors, 'form': formset, 'reports': Report.objects.all()}, context_instance=RequestContext(request)) else: return render_to_response('reports/reports.html',{ 'form': formset, 'reports': Report.objects.all()}, context_instance=RequestContext(request))
def edit_report(request, lot_number): report = Report.objects.get(lot_number=lot_number) if request.method == 'POST': reportform = ReportForm(request.POST, instance=report) if reportform.is_valid(): report = reportform.save() action.send(request.user, verb='edited lot number', target=report) return HttpResponseRedirect(report.get_absolute_url()) else: reportform = ReportForm(instance=report) return render_to_response('reports/new_report.html', {'reportform': reportform,}, context_instance=RequestContext(request))
def edit_report(request, lot_number): report = Report.objects.get(lot_number=lot_number) if request.method == 'POST': reportform = ReportForm(request.POST, instance=report) if reportform.is_valid(): report = reportform.save() action.send(request.user, verb='edited lot number', target=report) return HttpResponseRedirect(report.get_absolute_url()) else: reportform = ReportForm(instance=report) return render_to_response('reports/new_report.html', { 'reportform': reportform, }, context_instance=RequestContext(request))
def create_report_view(request): form = ReportForm(request.POST or None) if request.is_ajax(): image = request.POST.get('image') img = get_report_image(image) author_profile = Profile.objects.get(user=request.user) if form.is_valid(): instance = form.save(commit=False) instance.image = img instance.author = author_profile instance.save() return JsonResponse({'msg': 'success'}) return JsonResponse({})
def report(request, id): try: reported_elem = Node.objects.get(id=id) except: reported_elem = Edge.objects.get(id=id) if request.method == "POST": form = ReportForm(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.save() return redirect(reverse("reportdone")) else: form = ReportForm() return render(request, 'reports/report.html', { 'form': form, "element": reported_elem })
def index(request): if request.user.is_authenticated: if request.method == 'GET': form = ReportForm(data=request.POST, user_from=request.user.username) context = {'form': form} return render(request, 'reports/report.html', context) if request.method == 'POST': form = ReportForm(data=request.POST, user_from=request.user.username) if form.is_valid(): instance = form.save() report_reverse = instance.pk return redirect( reverse('reports:status', kwargs={'report_id': str(report_reverse)})) else: return redirect(reverse('user:login'))
def list_file(request): ''' :param request: :return:a response ''' report_form = ReportForm(request.POST or None) file_form = FileForm(request.POST or None, request.FILES or None) if file_form.is_valid(): collection_name = create_collection(request, file_form) instance = file_form.save(commit=False) instance.collection = collection_name instance.save() collection_obj = get_collection(request, collection_name) field_list, _ = get_fields_and_data_from_collection(collection_obj) field_instance_list = [] for turn in field_list: field_instance_list.append( Field.objects.create(name=turn[0], type=turn[1], file=instance)) print(Field.objects.all()) return redirect(reverse('files:list')) elif report_form.is_valid(): instance = report_form.save() narrative_instance = Narrative.objects.create(report=instance) narrative_instance.segments.create(index=0) print(instance.name, instance.file) return redirect(reverse('reports:editor', kwargs={'id': instance.id})) else: file_qs = File.objects.all() collection_list = [] for turn in file_qs: collection_list.append(get_summary_of_collection(request, turn)) context = { 'collection_list': collection_list, 'file_form': file_form, 'report_form': report_form, } return render(request, 'files/list.html', context)
def new_report(request): if request.method == 'POST': reportform = ReportForm(request.POST) if reportform.is_valid(): report = reportform.save() report.created_by = request.user report.save() action.send(request.user, verb='created lot number', action_object=report, target=report) return HttpResponseRedirect(report.get_absolute_url()) else: copy = request.GET.get('copy', None) if copy: report = Report.objects.get(lot_number=copy) reportform = ReportForm(instance=report) else: reportform = ReportForm(initial={'receiving_date': time.strftime("%Y-%m-%d")}) return render_to_response('reports/new_report.html', {'reportform': reportform,}, context_instance=RequestContext(request))
def report_list(request): # If we have an account_id provided via URI, using it as inital # value for the form. language = get_language() decimal_separator = get_format("DECIMAL_SEPARATOR", language, True) context = {"account": None, 'user': request.user} if not request.user.accounts.real_ib().exists(): return {"TEMPLATE": "reports/403.html"} excluded_for_user = set( AccountGroup.objects.excluded_for_user(request.user)) if request.method == "POST": form = ReportForm(data=request.POST or None, **context) if form.is_valid(): error_context = { "form": form, 'DECIMAL_SEPARATOR': decimal_separator, 'should_show_form': True, "reports": SavedReport.objects.filter( for_user=request.user).order_by('-creation_ts') } error_context.update(context) def error(): messages.error( request, _("You aren't allowed to view reports of that type for account" )) return error_context codename = form.cleaned_data.get("report_type") if not codename: return error() report = settings.REPORTS.get(codename) if not report: return error() account = None groups_to_include = None groups_to_exclude = None if report["type"] == reports.ACCOUNT_GROUP: groups_to_include = form.cleaned_data.get( "account_group_include") # мы хотим проверить, есть ли указанные пользователем группы среди доступных ему # - если в форме указаны группы, то проверяем их вхождения # - если они в форме не были указаны (для групп включения это означает использовать все счета), # то если юзер имеет разрешение reports.can_use_any_account - ему это разрешено, иначе нет. # так как set([None]) не является подмножеством ни пустого сета, ни реального, # то он покажет ошибку при проверке вхождений множеств. # set() является подмножеством любого сета и гарантированно пройдет проверку вхождения if groups_to_include: groups_to_include = set(groups_to_include) else: groups_to_include = set() if request.user.has_perm("reports.can_use_any_account") \ else set([None]) groups_to_exclude = form.cleaned_data.get( "account_group_exclude") groups_to_exclude = set( groups_to_exclude) if groups_to_exclude else set() available_inclusion_groups = set( AccountGroup.objects.for_user(request.user)) available_exclusion_groups = available_inclusion_groups | excluded_for_user if (groups_to_include and not groups_to_include.issubset(available_inclusion_groups)) or \ (groups_to_exclude and not groups_to_exclude.issubset(available_exclusion_groups)): return error() elif report["type"] == reports.GLOBAL: if not request.user.has_perm("reports.can_use_any_account"): return error() elif report["type"] == reports.PRIVATE_OFFICE: pass # No checks are required else: if not request.user.has_perm("reports.can_use_any_account"): account = form.cleaned_data.get("account") if account and account.user != request.user: return error() else: account = TradingAccount( mt4_id=int(request.POST.get("account"))) if not request.user.has_perm("reports.can_generate_%s" % codename): return error() template = report.get( 'template_name') or "reports/%s.html" % codename report = SavedReport() report.for_user = request.user report.name = unicode(form) % settings.REPORTS[codename]["name"] report.save() form_data = { 'account_group_include': groups_to_include or [], 'account_group_exclude': groups_to_exclude or [], 'account': account, 'report_type': codename, 'start': form.cleaned_data['start'], 'end': form.cleaned_data['end'], } task = generate_report.delay(form_data, template, decimal_separator, report, language, request.user) report.celery_task_id = task.pk report.save() messages.success( request, _("Your report order has been received and is now being processed. \ You will receive an email when the processing finishes.") ) return redirect("reports_report_list") else: today = date.today() form = ReportForm(initial={ "start": today + relativedelta(day=1), "end": today + relativedelta(day=1, days=-1, months=1) }, **context) context["form"] = form context["reports"] = SavedReport.objects.filter( for_user=request.user).order_by('-creation_ts') context['DECIMAL_SEPARATOR'] = decimal_separator context['should_show_form'] = True context['excluded_for_user'] = excluded_for_user return context
def reports_edit(request, **kwargs): # Get id report_id = kwargs.get('id') # Get current user's reports user_reports = request.user.report_set.all() # Check if the `report_id` is correct try: report_to_edit = user_reports.get(id=report_id) except: return render(request, 'error_page.html', context={ 'error_message': "No report with id:" + str(report_id) + " was found!" }) # Create the formset, specifying the form and formset we want to use ReportElementFormSet = formset_factory(ReportElementForm, formset=BaseFormSet, extra=0) # Get our data for. This is used as initial data. report_elements = ReportElement.objects.filter( report=report_to_edit).order_by("element_order") report_elements_count = report_elements.count() if request.method == 'POST': if request.POST.get('delete'): return redirect('reports_delete', id=report_id) report_form = ReportForm(request.POST) report_element_formset = ReportElementFormSet( request.POST, form_kwargs={'user': request.user}) if report_form.is_valid() and report_element_formset.is_valid(): report_new_data = report_form.cleaned_data # Update `report` object for attr, value in report_new_data.items(): # print('{} = {}'.format(attr, value)) setattr(report_to_edit, attr, value) report_to_edit.save() # Now save the data for each form in the formset new_elements = [] for form in report_element_formset: new_data = form.cleaned_data new_element = ReportElement(report=report_to_edit) for attr, value in new_data.items(): # print('{} = {}'.format(attr, value)) setattr(new_element, attr, value) new_elements.append(new_element) try: with transaction.atomic(): #Replace the old with the new ReportElement.objects.filter( report=report_to_edit).delete() ReportElement.objects.bulk_create(new_elements) # And notify our users that it worked messages.success( request, '<i class="uk-icon-floppy-o"></i> Report saved!', extra_tags='safe') except IntegrityError: #If the transaction failed messages.error( request, '<i class="uk-icon-ban"></i> There was an error saving your report.', extra_tags='safe') if request.POST.get('add'): return redirect('reports_add_element', id=report_id) else: report_form = ReportForm( initial={ 'report_name': report_to_edit.report_name, 'report_description': report_to_edit.report_description, }) report_element_formset = ReportElementFormSet( initial=[{ 'id': el.id, 'element_name': el.element_name, 'element_order': el.element_order, 'element_type': el.element_type, 'text': el.text, 'caption': el.caption, 'style': el.style, 'spreadsheet': el.spreadsheet, 'plot': el.plot, 'embedded_raport': el.embedded_raport, 'element_start': el.element_start, 'element_end': el.element_end, } for el in report_elements], form_kwargs={'user': request.user}) return render(request, 'reports_edit.html', context={ 'report': report_to_edit, 'report_form': report_form, 'report_element_formset': report_element_formset, 'report_elements_count': report_elements_count, })