def post(self, *args, **kwargs): to = self.request.POST.get('status', '') if self.order.status in (Order.STATUS_PENDING, Order.STATUS_EXPIRED) and to == 'p': try: mark_order_paid(self.order, manual=True, user=self.request.user) except Quota.QuotaExceededException as e: messages.error(self.request, str(e)) else: messages.success(self.request, _('The order has been marked as paid.')) elif self.order.status == Order.STATUS_PENDING and to == 'c': cancel_order(self.order, user=self.request.user) messages.success(self.request, _('The order has been cancelled.')) elif self.order.status == Order.STATUS_PAID and to == 'n': self.order.status = Order.STATUS_PENDING self.order.payment_manual = True self.order.save() self.order.log_action('pretix.event.order.unpaid', user=self.request.user) messages.success(self.request, _('The order has been marked as not paid.')) elif self.order.status == Order.STATUS_PENDING and to == 'e': self.order.status = Order.STATUS_EXPIRED self.order.save() self.order.log_action('pretix.event.order.expired', user=self.request.user) messages.success(self.request, _('The order has been marked as expired.')) elif self.order.status == Order.STATUS_PAID and to == 'r': ret = self.payment_provider.order_control_refund_perform(self.request, self.order) if ret: return redirect(ret) return redirect(self.get_order_url())
def _should_abort_user(request, should_redirect): # authorize if user is staff if request.user.is_staff: return False # authorize if user is female and not blocked not_female = False blocked = False if hasattr(request.user, 'profile'): if request.user.profile.gender == Profile.FEMALE: if not request.user.profile.blocked: return False else: blocked = True else: not_female = True auth_logout(request) if should_redirect: if not_female: return redirect(resolve_url('female_only')) elif blocked: return redirect(resolve_url('blocked')) return HttpResponseForbidden()
def initial_setup(request): if User.objects.all().exists(): return redirect('/comic/') if request.POST: form = InitialSetupForm(request.POST) if form.is_valid(): user = User( username=form.cleaned_data['username'], email=form.cleaned_data['email'], is_staff=True, is_superuser=True, ) user.set_password(form.cleaned_data['password']) user.save() base_dir, _ = Setting.objects.get_or_create(name='BASE_DIR') base_dir.value = form.cleaned_data['base_dir'] base_dir.save() user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password']) login(request, user) return redirect('/comic/') else: form = InitialSetupForm() context = { 'form': form, 'title': 'CBWebReader - Setup', 'error_message': form.errors, } return render(request, 'comic/settings_page.html', context)
def revisions_unschedule(request, page_id, revision_id): page = get_object_or_404(Page, id=page_id).specific user_perms = UserPagePermissionsProxy(request.user) if not user_perms.for_page(page).can_unschedule(): raise PermissionDenied revision = get_object_or_404(page.revisions, id=revision_id) next_url = get_valid_next_url_from_request(request) subtitle = _('revision {0} of "{1}"').format(revision.id, page.get_admin_display_title()) if request.method == 'POST': revision.approved_go_live_at = None revision.save(update_fields=['approved_go_live_at']) messages.success(request, _('Revision {0} of "{1}" unscheduled.').format(revision.id, page.get_admin_display_title()), buttons=[ messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit')) ]) if next_url: return redirect(next_url) return redirect('wagtailadmin_pages:revisions_index', page.id) return render(request, 'wagtailadmin/pages/revisions/confirm_unschedule.html', { 'page': page, 'revision': revision, 'next': next_url, 'subtitle': subtitle })
def _wrapped_view(request, *args, **kwargs): mv = MessageVerification.objects.get(user=request.user) if not mv.verified: return redirect(reverse("accounts.views.sms_verify")) if not request.user.profile.activated: return redirect(reverse("accounts.views.not_activated")) return view_func(request, *args, **kwargs)
def login_page(request): """ Display the login form. """ csrf_token = csrf(request)['csrf_token'] if (settings.FEATURES['AUTH_USE_CERTIFICATES'] and ssl_get_cert_from_request(request)): # SSL login doesn't require a login view, so redirect # to course now that the user is authenticated via # the decorator. next_url = request.GET.get('next') if next_url: return redirect(next_url) else: return redirect('/course/') if settings.FEATURES.get('AUTH_USE_CAS'): # If CAS is enabled, redirect auth handling to there return redirect(reverse('cas-login')) return render_to_response( 'login.html', { 'csrf': csrf_token, 'forgot_password_link': "//{base}/login#forgot-password-modal".format(base=settings.LMS_BASE), 'platform_name': microsite.get_value('platform_name', settings.PLATFORM_NAME), } )
def comic_list(request, directory_selector=False): try: base_dir = Setting.objects.get(name='BASE_DIR').value except Setting.DoesNotExist: return redirect('/comic/settings/') if not path.isdir(base_dir): return redirect('/comic/settings/') if directory_selector: selector = uuid.UUID(bytes=urlsafe_base64_decode(directory_selector)) directory = Directory.objects.get(selector=selector) else: directory = False if directory: title = generate_title_from_path(directory.path) breadcrumbs = generate_breadcrumbs_from_path(directory) json_url = '/comic/list_json/{0}/'.format(directory_selector) else: title = generate_title_from_path('Home') breadcrumbs = generate_breadcrumbs_from_path() json_url = '/comic/list_json/' return render(request, 'comic/comic_list.html', { 'breadcrumbs': breadcrumbs, 'menu': Menu(request.user, 'Browse'), 'title': title, 'json_url': json_url })
def doLogin(request): user = authenticate(username=request.POST["username"], password=request.POST["password"]) if user is not None: login(request, user) return redirect('/importlist/') else: return redirect('/?error=用户名或密码错误!')
def filmbody(request, f_id): try: film = Film.objects.get(id=f_id) if film.is_deleted is True: return redirect('/') except Film.DoesNotExist: return redirect('/') user = auth.get_user(request) mark_form = MarkForm() comment_form = CommentForm() if user.is_authenticated(): try: current_mark = Mark.objects.get(user=user, film=Film.objects.get(pk=f_id)) except Mark.DoesNotExist: current_mark = None else: current_mark = None if current_mark: current_mark = current_mark.number all_comments = Comment.objects.all().filter(film_id=f_id, is_deleted=False) average_mark = Mark.objects.average_mark(f_id) mark_dataset = Mark.objects.get_mark_dataset(f_id) context = { 'mark_form': mark_form, 'all_comments': all_comments, 'comment_form': comment_form, 'film': film, 'mark': current_mark, 'average_mark': average_mark, 'user': user, 'mark_dataset': json.dumps(mark_dataset), } return render(request, 'filmbody.html', context)
def the_challenge_page(request, challenge_id, state_engine=None, state=None): challenge = get_object_or_404(Challenge, id=challenge_id) challenge_recipient = challenge.recipient template_data = { 'challenge': challenge, 'challenge_recipient': challenge_recipient} challenge_tree = challenge.challenge_tree challenge_tree_stats = extract_statistics_from_challenge_tree(challenge_tree) template_data['challenge_tree_stats'] = challenge_tree_stats try: if state_engine: if request.is_ajax() or (state in [_StateEngineStates.PAY] and request.POST): return challenge_state_engine(request, challenge, state_engine, state) if not request.current_role: raise Http404 participation = ChallengeParticipation.objects.get( challenge=challenge, participating_entity_id=request.current_role.entity.id, participating_entity_type=request.current_role.entity_type) if participation.state_engine != state_engine: participation.state_engine = state_engine participation.save() template_data['challenge_participation'] = participation except Http404: logging.error("Tried to access a state engine page with out logging in") return redirect('/challenges/%s' % challenge_id) except ChallengeParticipation.DoesNotExist: logging.error("Tried to access a state engine but no participation found") return redirect('/challenges/%s' % challenge_id) return render(request, 'spudderspuds/challenges/pages/challenge_page.html', template_data)
def in_app_config(request, addon_id, addon, webapp=True): inapp = addon.premium_type in amo.ADDON_INAPPS if not inapp: messages.error(request, _('Your app is not configured for in-app payments.')) return redirect(reverse('mkt.developers.apps.payments', args=[addon.app_slug])) try: account = addon.app_payment_account except ObjectDoesNotExist: messages.error(request, _('No payment account for this app.')) return redirect(reverse('mkt.developers.apps.payments', args=[addon.app_slug])) seller_config = get_seller_product(account) owner = acl.check_addon_ownership(request, addon) if request.method == 'POST': # Reset the in-app secret for the app. (client.api.generic .product(seller_config['resource_pk']) .patch(data={'secret': generate_key(48)})) messages.success(request, _('Changes successfully saved.')) return redirect(reverse('mkt.developers.apps.in_app_config', args=[addon.app_slug])) return jingo.render(request, 'developers/payments/in-app-config.html', {'addon': addon, 'owner': owner, 'seller_config': seller_config})
def login(request): if request.user.is_authenticated(): return redirect('/') if request.method == 'POST': login_form = forms.LoginForm(request.POST) if login_form.is_valid(): login_name=request.POST['username'].strip() login_password=request.POST['password'] user = authenticate(username=login_name, password=login_password) if user is not None: if user.is_active: auth.login(request, user) messages.add_message(request, messages.SUCCESS, '成功登录了') return redirect('/') else: messages.add_message(request, messages.WARNING, '账号尚未启用') else: messages.add_message(request, messages.WARNING, '登录失败') else: messages.add_message(request, messages.INFO,'请检查输入的字段内容') else: login_form = forms.LoginForm() template = get_template('login.html') request_context = RequestContext(request) request_context.push(locals()) html = template.render(request_context) return HttpResponse(html)
def register(request): form = ChallengesRegisterForm( initial=request.GET, enable_register_club=feature_is_enabled('challenge_register_club')) if request.method == "POST": form = ChallengesRegisterForm(request.POST, enable_register_club=feature_is_enabled('challenge_register_club')) if form.is_valid(): username = form.cleaned_data.get('email_address') password = form.cleaned_data.get('password') user = User.objects.create_user(username, username, password) user.save() user.spudder_user.mark_password_as_done() fan_entity = create_and_activate_fan_role(request, user) fan_page = fan_entity.entity fan_page.username = form.cleaned_data.get('username') fan_page.state = str(request.META.get('HTTP_X_APPENGINE_REGION')).upper() fan_page.save() login(request, authenticate(username=username, password=password)) if feature_is_enabled('tracking_pixels'): EventController.RegisterEvent(request, EventController.CHALLENGER_USER_REGISTERER) if form.cleaned_data.get('account_type') == EntityController.ENTITY_CLUB: return redirect('/challenges/register/team?next=%s' % form.cleaned_data.get('next', '/')) return redirect(form.cleaned_data.get('next', '/')) return render( request, 'spudderspuds/challenges/pages/register.html', {'form': form})
def login_view(request): context = {} context['form'] = UserLogin(initial={'next_page': request.GET.get('next')}) if request.method == "POST": form = UserLogin(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] next_page = form.cleaned_data['next_page'] auth_user = authenticate(username=username, password=password) if auth_user is not None: if auth_user.is_active: login(request, auth_user) context['valid'] = "Login Successful" print next_page if next_page == None or next_page == "": return redirect('candidate_list_view') else: return redirect(next_page) else: context['valid'] = "Invalid User" else: context['valid'] = "Login Failed! Try again" return render_to_response('login_view.html', context, context_instance=RequestContext(request))
def speaker_create(request): try: return redirect(request.user.speaker_profile) except ObjectDoesNotExist: pass if request.method == "POST": try: speaker = Speaker.objects.get(invite_email=request.user.email) found = True except Speaker.DoesNotExist: speaker = None found = False form = SpeakerForm(request.POST, request.FILES, instance=speaker) if form.is_valid(): speaker = form.save(commit=False) speaker.user = request.user if not found: speaker.invite_email = None speaker.save() messages.success(request, "Speaker profile created.") return redirect("speaker_dashboard") else: form = SpeakerForm() ctx = { "form": form, } ctx = RequestContext(request, ctx) return render_to_response("speakers/speaker_create.html", ctx)
def chpass(request): """ Change user's password """ if request.method == 'POST': f = PasswordResetForm(request.POST) if f.is_valid(): current = f.cleaned_data['current'] password = f.cleaned_data['password'] user = User.objects.get(pk=request.user.id) username = user.username chk = auth.authenticate(username = username, password = current) if chk is not None: if chk.is_active: user.set_password(password) user.save() messages.add_message(request, messages.SUCCESS, _('Settings saved')) return redirect('user:index') else: messages.add_message(request, messages.ERROR, _('Your current password is invalid.')) return redirect(reverse('user:chpass')) else: return HttpResponse(_('Form invalid')) f = PasswordResetForm() ctx = { 'title': _('Change password'), 'form': f, } return render(request, 'userspace/chpass.html', ctx)
def userlogin(request): if request.user.is_authenticated(): return redirect('IndexViewWeb') else: if request.method == "POST": if 'login_form' in request.POST: login_form = userLoginForm(request.POST) if login_form.is_valid(): user = authenticate(username=login_form.cleaned_data[ 'username'], password=login_form.cleaned_data['password']) if user is not None: if user.is_active: try: login(request, user) return redirect('indexDashboard') except: errors = ''' <div class="card-panel teal lighten-2">User Activo</div> ''' return render(request, 'login.html', {'login_form': login_form, 'errors': errors}) else: errors = ''' <div class="card-panel red lighten-2"><span class="white-text">Usuario y/o contraseña incorrecta.</span></div> ''' return render(request, 'login.html', {'login_form': login_form, 'errors': errors}) else: raise Exception('Error Login : Form incomplete') else: errors = '' login_form = userLoginForm() return render(request, 'login.html', {'login_form': login_form, 'errors': errors})
def requests(request, group_id): try: grp = Group.objects.get(id=int(group_id)) except: raise Http404 if grp.teacher != request.user: return HttpResponse(status=403) if request.method == 'POST': try: jr = JoinRequest.objects.get(id=int(request.POST['request_id'])) request.POST['action'] if jr.group != grp: raise Exception except: return redirect('/teacher/groups/%s/requests/' % (grp.id, )) if request.POST['action'] == 'confirm': jr.execute() messages.add_message(request, messages.SUCCESS, u'Zaakceptowano') else: jr.delete() messages.add_message(request, messages.SUCCESS, u'Usunięto wniosek') return redirect('/teacher/groups/%s/requests/' % (grp.id, )) return render_to_response('rteacher/manage_groups_requests.html', request, **klist( selected_group_id=grp.id, request=request, group=grp))
def download_xls(request, course_uuid): course = CourseDetail.objects.get(course_uuid = course_uuid, teacher = request.user) # user_list = [] if course: _users_enroll_course = EnrolledCourses.objects.filter(course = course) # user_list = [enroll_course.user for enroll_course in _users_enroll_course] try: assert _users_enroll_course,'Assert Error: Not have any user' except Exception as e: messages.info(request, 'Unable to find enrolled user(s) in this course.') return redirect('/teacher/manage/'+course_uuid) _sm_course_name = 'course_id_'+str(course.id) if create_users_xls(users_enroll_course = _users_enroll_course, _sm_course_name = _sm_course_name, course_name = course.course_name): dir_name = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) file_dir_path = 'xls/'+_sm_course_name filename = dir_name+'/'+file_dir_path+'/enrolled_user.xls' wrapper = FileWrapper(file(filename)) response = HttpResponse(wrapper, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(filename) response['Content-Length'] = os.path.getsize(filename) return response else: messages.error(request,'Error in your request please try again after some time.') return redirect('/teacher/manage/'+course_uuid)
def save_content_order(request): try: common_page_data = get_common_page_data(request, request.POST.get("course_prefix"), request.POST.get("course_suffix")) except: raise Http404 if not common_page_data['is_course_admin']: return redirect('courses.views.main', request.POST.get("course_prefix"), request.POST.get("course_suffix")) SECTION = ContentSection.objects.get(pk=request.POST.get('section_id')) section_structures = get_course_materials(common_page_data=common_page_data, get_video_content=True, get_additional_page_content = True, get_file_content=True, get_exam_content=True, SECTION=SECTION) def set_index_from_POST(item): tag = item['type'] image = item[tag].image new_index = request.POST.get("order_"+tag+"_"+str(item[tag].id)) item[tag].index = new_index item[tag].save() image.index = new_index image.save() for section_structure in section_structures: for item in section_structure['items']: set_index_from_POST(item) return redirect(request.META['HTTP_REFERER'])
def post(self,request,*args,**kwargs): username = request.POST['usuario'] password = request.POST['password'] user = authenticate(username=username,password=password) if user is not None: if user.is_active: request.session['usuario'] = user.id #sets the exp. value of the session login(request, user) #the user is now logged in # if request.user.is_authenticated(): # mensaje = u'¡Ha cerrado sesión correctamente!' # messages.info(self.request, mensaje) # return redirect(reverse_lazy('login')) # return render(request, 'rcs/dashboard.html',context) return redirect(reverse_lazy('dashboard')) else: return redirect(reverse_lazy('login')) else: mensaje_error= 'El usuario o contraseña es invalido.' errors = { 'mensaje_error': mensaje_error, } return render(request, 'index.html', errors)
def edit_pool(request, uuid=None): title = 'Edit Pool' if uuid: thisObj = get_object_or_404(pool, poolID=uuid) if request.POST: if request.POST.get("_cancel"): return redirect(reverse('pool_list')) else: form = poolForm(request.POST, instance=thisObj) if form.is_valid(): form.save() if request.POST.get("_stay"): context = {"title": title, "form": form} return render(request, "pool/pool.html", context) else: return redirect(reverse('pool_list')) else: context = {"title": title, "form": form} return render(request, "pool/pool.html", context) else: form = poolForm(instance=thisObj) context = {"title": title, "form": form} return render(request, "pool/pool.html", context)
def edit_contact(request, uuid=None): title = 'Edit Contact' if uuid: thisObj = get_object_or_404(contact, ctID=uuid) if request.POST: if request.POST.get("_cancel"): return redirect(reverse('contact_list')) else: form = contactForm(request.POST, instance=thisObj) if form.is_valid(): form.save() if request.POST.get("_stay"): context = {"title": title, "form": form} return render(request, "contact/contact.html", context) else: return redirect(reverse('contact_list')) else: context = {"title": title, "form": form} return render(request, "contact/contact.html", context) else: form = contactForm(instance=thisObj) context = { "title": title, "form": form } return render(request, "contact/contact.html", context)
def edit_hardware(request, uuid=None): title = 'Edit Hardware' if uuid: thisObj = get_object_or_404(hardware, hwID=uuid) if request.POST: if request.POST.get("_cancel"): return redirect(reverse('hardware_list')) else: form = hardwareForm(request.POST, instance=thisObj) if form.is_valid(): form.save() if request.POST.get("_stay"): context = {"title": title, "form": form} return render(request, "hardware/hardware.html", context) else: return redirect(reverse('hardware_list')) else: context = {"title": title, "form": form} return render(request, "hardware/hardware.html", context) else: form = hardwareForm(instance=thisObj) context = {"title": title, "form": form} return render(request, "hardware/hardware.html", context)
def new_contact(request): title = 'New Contact' form = contactForm(request.POST or None) if request.POST: if request.POST.get("_cancel"): return redirect(reverse('contact_list')) else: form = contactForm(request.POST) if form.is_valid(): form.save() obj = form.instance if request.POST.get("_stay"): return redirect(reverse('contact_edit', kwargs={'uuid': obj.pk} )) else: return redirect(reverse('contact_list')) else: context = {"title": title, "form": form} return render(request, "contact/contact.html", context) context = { "title": title, "form": form } return render(request, "contact/contact.html", context)
def unpublish(request, page_id): page = get_object_or_404(Page, id=page_id).specific user_perms = UserPagePermissionsProxy(request.user) if not user_perms.for_page(page).can_unpublish(): raise PermissionDenied next_url = get_valid_next_url_from_request(request) if request.method == 'POST': include_descendants = request.POST.get("include_descendants", False) page.unpublish() if include_descendants: live_descendant_pages = page.get_descendants().live().specific() for live_descendant_page in live_descendant_pages: if user_perms.for_page(live_descendant_page).can_unpublish(): live_descendant_page.unpublish() messages.success(request, _("Page '{0}' unpublished.").format(page.get_admin_display_title()), buttons=[ messages.button(reverse('wagtailadmin_pages:edit', args=(page.id,)), _('Edit')) ]) if next_url: return redirect(next_url) return redirect('wagtailadmin_explore', page.get_parent().id) return render(request, 'wagtailadmin/pages/confirm_unpublish.html', { 'page': page, 'next': next_url, 'live_descendant_count': page.get_descendants().live().count(), })
def post(request): assert (request.method == 'POST') db_name = request.POST['db'] sequence = request.POST['sequence'] try: hash = models.Giraffe_Mappable_Model.detect_features(sequence,db_name) if 'next' in request.POST: u = request.POST['next'] if u.endswith('/'): u = u+hash+'/'+db_name else: u = u+'/'+hash+'/'+db_name return redirect(u) return redirect(reverse(get,args=[hash,db_name])) except Exception as e: # print 'Blat error on sequence: '+str(sequence) if 'next' in request.POST: print str(e) u = request.POST['next'] if u.endswith('/'): u = u+'error/' else: u = u+'/error/' return redirect(u) raise e
def new_pool(request): title = 'New Pool' form = poolForm(request.POST or None) if request.POST: if request.POST.get("_cancel"): return redirect(reverse('pool_list')) else: form = poolForm(request.POST) if form.is_valid(): form.save() obj = form.instance if request.POST.get("_stay"): return redirect(reverse('pool_edit', kwargs={'uuid': obj.pk} )) else: return redirect(reverse('pool_list')) else: context = {"title": title, "form": form} return render(request, "pool/pool.html", context) else: context = {"title": title, "form": form} return render(request, "pool/pool.html", context)
def delete(request, page_id): page = get_object_or_404(Page, id=page_id).specific if not page.permissions_for_user(request.user).can_delete(): raise PermissionDenied with transaction.atomic(): for fn in hooks.get_hooks('before_delete_page'): result = fn(request, page) if hasattr(result, 'status_code'): return result next_url = get_valid_next_url_from_request(request) if request.method == 'POST': parent_id = page.get_parent().id page.delete() messages.success(request, _("Page '{0}' deleted.").format(page.get_admin_display_title())) for fn in hooks.get_hooks('after_delete_page'): result = fn(request, page) if hasattr(result, 'status_code'): return result if next_url: return redirect(next_url) return redirect('wagtailadmin_explore', parent_id) return render(request, 'wagtailadmin/pages/confirm_delete.html', { 'page': page, 'descendant_count': page.get_descendant_count(), 'next': next_url, })
def delete(request, user_id): if request.method == 'POST': user = User.objects.get(pk=user_id) user.delete() return redirect("/usuarios/") else: return redirect("/usuarios/")
def access_delete(request, id): access = get_object_or_404(models.Access, pk=id) access.delete() return redirect("main.views.access_list")
def remove_cart_item(request): cart_item_id = request.POST.get('cart_item_id') cartItem = CartItem.objects.get(pk=cart_item_id) cartItem.delete() return redirect(cart)
def logout(request): del request.session['user_id'] return redirect('/')
def login_user(request): login = User.objects.login_user(request,request.POST) if login[0]: request.session['user_id'] = login[1].id return redirect('/home') return redirect('/')
def post(self, request, *args, **kwargs): survey = get_object_or_404(Survey, is_published=True, id=kwargs["id"]) if survey.need_logged_user and not request.user.is_authenticated: return redirect("%s?next=%s" % (settings.LOGIN_URL, request.path)) categories = Category.objects.filter(survey=survey).order_by("order") form = ResponseForm( request.POST, survey=survey, user=request.user, step=kwargs.get("step", 0) ) if not survey.editable_answers and form.response is not None: LOGGER.info( "Redirects to survey list after trying to edit non editable answer." ) return redirect(reverse("survey-list")) context = {"response_form": form, "survey": survey, "categories": categories} if form.is_valid(): session_key = "survey_%s" % (kwargs["id"],) if session_key not in request.session: request.session[session_key] = {} for key, value in list(form.cleaned_data.items()): request.session[session_key][key] = value request.session.modified = True next_url = form.next_step_url() response = None if survey.display_by_question: # when it's the last step if not form.has_next_step(): save_form = ResponseForm( request.session[session_key], survey=survey, user=request.user ) if save_form.is_valid(): response = save_form.save() else: LOGGER.warning( "A step of the multipage form failed \ but should have been discovered before." ) else: response = form.save() # if there is a next step if next_url is not None: return redirect(next_url) else: del request.session[session_key] if response is None: return redirect(reverse("survey-list")) else: next_ = request.session.get("next", None) if next_ is not None: if "next" in request.session: del request.session["next"] return redirect(next_) else: return redirect( "survey-confirmation", uuid=response.interview_uuid ) else: LOGGER.info("Non valid form: <%s>", form) if survey.template is not None and len(survey.template) > 4: template_name = survey.template else: if survey.display_by_question: template_name = "survey/survey.html" else: template_name = "survey/one_page_survey.html" return render(request, template_name, context)
def root(request): # TODO: 차후에 URL Reverse 기능 검토 예정 #return HttpResponseRedirect('/blog/') return redirect('shop:index')
def post_publish(request, pk): post = get_object_or_404(Post, pk=pk) post.publish() return redirect('post_detail', pk=pk)
def signout(request): logout(request) return redirect('app:login')
def logout(request): request.session.flush() return redirect('/')
def import_documents(request): def is_reserved_directory(doc): return doc['fields']['type'] == 'directory' and doc['fields'][ 'name'] in (Document2.HOME_DIR, Document2.TRASH_DIR) try: if request.FILES.get('documents'): documents = request.FILES['documents'].read() else: documents = json.loads(request.POST.get('documents')) documents = json.loads(documents) except ValueError as e: raise PopupException( _('Failed to import documents, the file does not contain valid JSON.' )) # Validate documents if not _is_import_valid(documents): raise PopupException( _('Failed to import documents, the file does not contain the expected JSON schema for Hue documents.' )) docs = [] uuids_map = dict((doc['fields']['uuid'], None) for doc in documents if not is_reserved_directory(doc)) for doc in documents: # Filter docs to import, ignoring reserved directories (home and Trash) and history docs if not is_reserved_directory(doc): # Remove any deprecated fields if 'tags' in doc['fields']: doc['fields'].pop('tags') # If doc is not owned by current user, make a copy of the document with current user as owner if doc['fields']['owner'][0] != request.user.username: doc = _copy_document_with_owner(doc, request.user, uuids_map) else: # Update existing doc or create new doc = _create_or_update_document_with_owner( doc, request.user, uuids_map) # For oozie docs replace dependent uuids with the newly created ones if doc['fields']['type'].startswith('oozie-'): doc = _update_imported_oozie_document(doc, uuids_map) # If the doc contains any history dependencies, ignore them # NOTE: this assumes that each dependency is exported as an array using the natural PK [uuid, version, is_history] deps_minus_history = [ dep for dep in doc['fields'].get('dependencies', []) if len(dep) >= 3 and not dep[2] ] doc['fields']['dependencies'] = deps_minus_history # Replace illegal characters if '/' in doc['fields']['name']: new_name = doc['fields']['name'].replace('/', '-') LOG.warn( "Found illegal slash in document named: %s, renaming to: %s." % (doc['fields']['name'], new_name)) doc['fields']['name'] = new_name # Set last modified date to now doc['fields']['last_modified'] = datetime.now().replace( microsecond=0).isoformat() docs.append(doc) f = tempfile.NamedTemporaryFile(mode='w+', suffix='.json') f.write(json.dumps(docs)) f.flush() stdout = string_io() try: with transaction.atomic( ): # We wrap both commands to commit loaddata & sync management.call_command('loaddata', f.name, verbosity=3, traceback=True, stdout=stdout) Document.objects.sync() if request.POST.get('redirect'): return redirect(request.POST.get('redirect')) else: return JsonResponse({ 'status': 0, 'message': stdout.getvalue(), 'count': len(documents), 'created_count': len([doc for doc in documents if doc['pk'] is None]), 'updated_count': len([doc for doc in documents if doc['pk'] is not None]), 'username': request.user.username, 'documents': [ dict([('name', doc['fields']['name']), ('uuid', doc['fields']['uuid']), ('type', doc['fields']['type']), ('owner', doc['fields']['owner'][0])]) for doc in docs ] }) except Exception as e: LOG.error('Failed to run loaddata command in import_documents:\n %s' % stdout.getvalue()) return JsonResponse({'status': -1, 'message': smart_str(e)}) finally: stdout.close()
def logout_view(request): """Ends an application session""" logout(request) return redirect('journal:index')
def get(self,request): if request.user.has_perm('webapp.add_signup_table'): return redirect('/admin') else: return redirect('/mobileanl/admin_setup') '''
def edit_coordinator(request, coordinator): history = History.objects.filter( submitter=request.user, job=coordinator).order_by('-submission_date') DatasetFormSet = inlineformset_factory(Coordinator, Dataset, form=DatasetForm, max_num=0, can_order=False, can_delete=True) DataInputFormSet = inlineformset_factory(Coordinator, DataInput, form=DataInputForm, max_num=0, can_order=False, can_delete=True) DataInputFormSet.form = staticmethod( curry(DataInputForm, coordinator=coordinator)) DataOutputFormSet = inlineformset_factory(Coordinator, DataOutput, form=DataOutputForm, max_num=0, can_order=False, can_delete=True) DataOutputFormSet.form = staticmethod( curry(DataOutputForm, coordinator=coordinator)) dataset = Dataset(coordinator=coordinator) dataset_form = DatasetForm(instance=dataset, prefix='create') NewDataInputFormSet = inlineformset_factory(Coordinator, DataInput, form=DataInputForm, extra=0, can_order=False, can_delete=False) NewDataInputFormSet.form = staticmethod( curry(DataInputForm, coordinator=coordinator)) NewDataOutputFormSet = inlineformset_factory(Coordinator, DataOutput, form=DataOutputForm, extra=0, can_order=False, can_delete=False) NewDataOutputFormSet.form = staticmethod( curry(DataOutputForm, coordinator=coordinator)) enable_cron_scheduling = ENABLE_CRON_SCHEDULING.get() if request.method == 'POST': coordinator_form = CoordinatorForm(request.POST, instance=coordinator, user=request.user) dataset_formset = DatasetFormSet(request.POST, request.FILES, instance=coordinator) data_input_formset = DataInputFormSet(request.POST, request.FILES, instance=coordinator) data_output_formset = DataOutputFormSet(request.POST, request.FILES, instance=coordinator) new_data_input_formset = NewDataInputFormSet(request.POST, request.FILES, instance=coordinator, prefix='input') new_data_output_formset = NewDataOutputFormSet(request.POST, request.FILES, instance=coordinator, prefix='output') if coordinator_form.is_valid() and dataset_formset.is_valid() and data_input_formset.is_valid() and data_output_formset.is_valid() \ and new_data_input_formset.is_valid() and new_data_output_formset.is_valid(): coordinator = coordinator_form.save() dataset_formset.save() data_input_formset.save() data_output_formset.save() new_data_input_formset.save() new_data_output_formset.save() coordinator.sla = json.loads(request.POST.get('sla')) if enable_cron_scheduling: coordinator.cron_frequency = { 'frequency': strip_tags(request.POST.get('cron_frequency')), 'isAdvancedCron': request.POST.get('isAdvancedCron') == 'on' } coordinator.save() request.info(_('Coordinator saved.')) return redirect( reverse('oozie:edit_coordinator', kwargs={'coordinator': coordinator.id})) else: coordinator_form = CoordinatorForm(instance=coordinator, user=request.user) dataset_formset = DatasetFormSet(instance=coordinator) data_input_formset = DataInputFormSet(instance=coordinator) data_output_formset = DataOutputFormSet(instance=coordinator) new_data_input_formset = NewDataInputFormSet( queryset=DataInput.objects.none(), instance=coordinator, prefix='input') new_data_output_formset = NewDataOutputFormSet( queryset=DataOutput.objects.none(), instance=coordinator, prefix='output') return render( 'editor/edit_coordinator.mako', request, { 'coordinator': coordinator, 'coordinator_form': coordinator_form, 'dataset_formset': dataset_formset, 'data_input_formset': data_input_formset, 'data_output_formset': data_output_formset, 'dataset': dataset, 'dataset_form': dataset_form, 'new_data_input_formset': new_data_input_formset, 'new_data_output_formset': new_data_output_formset, 'history': history, 'coordinator_frequency': json.dumps(coordinator.cron_frequency), 'enable_cron_scheduling': enable_cron_scheduling, })
def home(request): return redirect('deliverables:index')
def story_starr(request, pk): story = get_object_or_404(Story, pk=pk) request.user.userprofile.starred.add(story) return redirect('myapp:story_detail', pk=story.pk)
def logout (request): if request.method == 'POST': auth.logout(request) return redirect('home')
def logout(request): auth.logout(request) return redirect(request.GET.get('from', reverse('home')))
def user_logout(request): logout(request) return redirect('/')
def get(self, request): groups = request.user.groups.all().values_list('name', flat=True) if 'window_cleaner' in groups: return redirect("worksheets") else: return redirect("customers")
def logout(request): if not request.user.is_authenticated: return redirect('login') auth.logout(request) return redirect('login')
def choose_language(request): #post the languague which user will use in the application if request.method == "POST": chosen_language = request.POST.get('language') return redirect('/farmer/'+ str(chosen_language) +'/farms/') return render(request, 'farmer/overview/language.html')
def finish_google_oauth2(request): # type: (HttpRequest) -> HttpResponse error = request.GET.get('error') if error == 'access_denied': return redirect('/') elif error is not None: logging.warning('Error from google oauth2 login: %s' % (request.GET.get("error"),)) return HttpResponse(status=400) csrf_state = request.GET.get('state') if csrf_state is None or len(csrf_state.split(':')) != 5: logging.warning('Missing Google oauth2 CSRF state') return HttpResponse(status=400) (csrf_data, hmac_value) = csrf_state.rsplit(':', 1) if hmac_value != google_oauth2_csrf(request, csrf_data): logging.warning('Google oauth2 CSRF error') return HttpResponse(status=400) cur_time, subdomain, mobile_flow_otp, is_signup = csrf_data.split(':') if mobile_flow_otp == '0': mobile_flow_otp = None is_signup = bool(is_signup == '1') resp = requests.post( 'https://www.googleapis.com/oauth2/v3/token', data={ 'code': request.GET.get('code'), 'client_id': settings.GOOGLE_OAUTH2_CLIENT_ID, 'client_secret': settings.GOOGLE_OAUTH2_CLIENT_SECRET, 'redirect_uri': reverse_on_root('zerver.views.auth.finish_google_oauth2'), 'grant_type': 'authorization_code', }, ) if resp.status_code == 400: logging.warning('User error converting Google oauth2 login to token: %s' % (resp.text,)) return HttpResponse(status=400) elif resp.status_code != 200: logging.error('Could not convert google oauth2 code to access_token: %s' % (resp.text,)) return HttpResponse(status=400) access_token = resp.json()['access_token'] resp = requests.get( 'https://www.googleapis.com/plus/v1/people/me', params={'access_token': access_token} ) if resp.status_code == 400: logging.warning('Google login failed making info API call: %s' % (resp.text,)) return HttpResponse(status=400) elif resp.status_code != 200: logging.error('Google login failed making API call: %s' % (resp.text,)) return HttpResponse(status=400) body = resp.json() try: full_name = body['name']['formatted'] except KeyError: # Only google+ users have a formatted name. I am ignoring i18n here. full_name = u'{} {}'.format( body['name']['givenName'], body['name']['familyName'] ) for email in body['emails']: if email['type'] == 'account': break else: logging.error('Google oauth2 account email not found: %s' % (body,)) return HttpResponse(status=400) email_address = email['value'] try: realm = Realm.objects.get(string_id=subdomain) except Realm.DoesNotExist: # nocoverage return redirect_to_subdomain_login_url() if mobile_flow_otp is not None: # When request was not initiated from subdomain. user_profile, return_data = authenticate_remote_user(realm, email_address) invalid_subdomain = bool(return_data.get('invalid_subdomain')) return login_or_register_remote_user(request, email_address, user_profile, full_name, invalid_subdomain, mobile_flow_otp=mobile_flow_otp, is_signup=is_signup) return redirect_and_log_into_subdomain( realm, full_name, email_address, is_signup=is_signup)
def add_room(request): form_room = RoomAdd(request.POST) if form_room.is_valid(): info = form_room.cleaned_data Room.objects.create(number_room=info['room_num']) return redirect('player:player')
def logout(request): #登出 auth.logout(request) return redirect('/index/')
def apagar(request, hash): db_slug = 'default' try: usuario_id = request.user.id dict_hash = get_hash_url(hash) s1210_detpgtofl_infopgtoparc_id = int(dict_hash['id']) for_print = int(dict_hash['print']) except: usuario_id = False return redirect('login') usuario = get_object_or_404(Usuarios.objects.using(db_slug), excluido=False, id=usuario_id) pagina = ConfigPaginas.objects.using(db_slug).get( excluido=False, endereco='s1210_detpgtofl_infopgtoparc') permissao = ConfigPermissoes.objects.using(db_slug).get( excluido=False, config_paginas=pagina, config_perfis=usuario.config_perfis) dict_permissoes = json_to_dict(usuario.config_perfis.permissoes) paginas_permitidas_lista = usuario.config_perfis.paginas_permitidas modulos_permitidos_lista = usuario.config_perfis.modulos_permitidos s1210_detpgtofl_infopgtoparc = get_object_or_404( s1210detPgtoFlinfoPgtoParc.objects.using(db_slug), excluido=False, id=s1210_detpgtofl_infopgtoparc_id) dados_evento = {} if s1210_detpgtofl_infopgtoparc_id: dados_evento = s1210_detpgtofl_infopgtoparc.evento() if dados_evento['status'] != 0: dict_permissoes['s1210_detpgtofl_infopgtoparc_apagar'] = 0 dict_permissoes['s1210_detpgtofl_infopgtoparc_editar'] = 0 if request.method == 'POST': if dados_evento['status'] == 0: import json from django.forms.models import model_to_dict situacao_anterior = json.dumps( model_to_dict(s1210_detpgtofl_infopgtoparc), indent=4, sort_keys=True, default=str) s1210detPgtoFlinfoPgtoParc.objects.using(db_slug).filter( id=s1210_detpgtofl_infopgtoparc_id).delete() #s1210_detpgtofl_infopgtoparc_apagar_custom #s1210_detpgtofl_infopgtoparc_apagar_custom messages.success(request, 'Apagado com sucesso!') gravar_auditoria(situacao_anterior, '', 's1210_detpgtofl_infopgtoparc', s1210_detpgtofl_infopgtoparc_id, usuario_id, 3) else: messages.error( request, 'Não foi possivel apagar o evento, somente é possível apagar os eventos com status "Cadastrado"!' ) if request.session[ 'retorno_pagina'] == 's1210_detpgtofl_infopgtoparc_salvar': return redirect('s1210_detpgtofl_infopgtoparc', hash=request.session['retorno_hash']) else: return redirect(request.session['retorno_pagina'], hash=request.session['retorno_hash']) context = { 'usuario': usuario, 'modulos_permitidos_lista': modulos_permitidos_lista, 'paginas_permitidas_lista': paginas_permitidas_lista, 'permissao': permissao, 'data': datetime.datetime.now(), 'pagina': pagina, 'dict_permissoes': dict_permissoes, 'hash': hash, } return render(request, 's1210_detpgtofl_infopgtoparc_apagar.html', context)
def logout_request(request): logout(request) messages.info(request, "You have sucessfully logged out.") return redirect("login")
def listar(request, hash): for_print = 0 db_slug = 'default' try: usuario_id = request.user.id dict_hash = get_hash_url(hash) #retorno_pagina = dict_hash['retorno_pagina'] #retorno_hash = dict_hash['retorno_hash'] #s1210_detpgtofl_infopgtoparc_id = int(dict_hash['id']) for_print = int(dict_hash['print']) except: usuario_id = False return redirect('login') usuario = get_object_or_404(Usuarios.objects.using(db_slug), excluido=False, id=usuario_id) pagina = ConfigPaginas.objects.using(db_slug).get( excluido=False, endereco='s1210_detpgtofl_infopgtoparc') permissao = ConfigPermissoes.objects.using(db_slug).get( excluido=False, config_paginas=pagina, config_perfis=usuario.config_perfis) dict_permissoes = json_to_dict(usuario.config_perfis.permissoes) paginas_permitidas_lista = usuario.config_perfis.paginas_permitidas modulos_permitidos_lista = usuario.config_perfis.modulos_permitidos if permissao.permite_listar: filtrar = False dict_fields = {} show_fields = { 'show_codrubr': 1, 'show_fatorrubr': 0, 'show_idetabrubr': 1, 'show_matricula': 0, 'show_qtdrubr': 0, 'show_s1210_detpgtofl': 1, 'show_vrrubr': 1, 'show_vrunit': 0, } post = False if request.method == 'POST': post = True dict_fields = { 'codrubr__icontains': 'codrubr__icontains', 'fatorrubr': 'fatorrubr', 'idetabrubr__icontains': 'idetabrubr__icontains', 'matricula__icontains': 'matricula__icontains', 'qtdrubr': 'qtdrubr', 's1210_detpgtofl': 's1210_detpgtofl', 'vrrubr': 'vrrubr', 'vrunit': 'vrunit', } for a in dict_fields: dict_fields[a] = request.POST.get(a or None) for a in show_fields: show_fields[a] = request.POST.get(a or None) if request.method == 'POST': dict_fields = { 'codrubr__icontains': 'codrubr__icontains', 'fatorrubr': 'fatorrubr', 'idetabrubr__icontains': 'idetabrubr__icontains', 'matricula__icontains': 'matricula__icontains', 'qtdrubr': 'qtdrubr', 's1210_detpgtofl': 's1210_detpgtofl', 'vrrubr': 'vrrubr', 'vrunit': 'vrunit', } for a in dict_fields: dict_fields[a] = request.POST.get(dict_fields[a] or None) dict_qs = clear_dict_fields(dict_fields) s1210_detpgtofl_infopgtoparc_lista = s1210detPgtoFlinfoPgtoParc.objects.using( db_slug).filter(**dict_qs).filter(excluido=False).exclude( id=0).all() if not post and len(s1210_detpgtofl_infopgtoparc_lista) > 100: filtrar = True s1210_detpgtofl_infopgtoparc_lista = None messages.warning( request, 'Listagem com mais de 100 resultados! Filtre os resultados um melhor desempenho!' ) #s1210_detpgtofl_infopgtoparc_listar_custom request.session["retorno_hash"] = hash request.session["retorno_pagina"] = 's1210_detpgtofl_infopgtoparc' context = { 's1210_detpgtofl_infopgtoparc_lista': s1210_detpgtofl_infopgtoparc_lista, 'usuario': usuario, 'modulos_permitidos_lista': modulos_permitidos_lista, 'paginas_permitidas_lista': paginas_permitidas_lista, 'permissao': permissao, 'dict_fields': dict_fields, 'data': datetime.datetime.now(), 'pagina': pagina, 'dict_permissoes': dict_permissoes, 'show_fields': show_fields, 'for_print': for_print, 'hash': hash, 'filtrar': filtrar, } if for_print in (0, 1): return render(request, 's1210_detpgtofl_infopgtoparc_listar.html', context) elif for_print == 2: #return render_to_pdf('tables/s1000_evtinfoempregador_pdf_xls.html', context) from wkhtmltopdf.views import PDFTemplateResponse response = PDFTemplateResponse( request=request, template='s1210_detpgtofl_infopgtoparc_listar.html', filename="s1210_detpgtofl_infopgtoparc.pdf", context=context, show_content_in_browser=True, cmd_options={ 'margin-top': 10, 'margin-bottom': 10, 'margin-right': 10, 'margin-left': 10, 'zoom': 1, 'dpi': 72, 'orientation': 'Landscape', "viewport-size": "1366 x 513", 'javascript-delay': 1000, 'footer-center': '[page]/[topage]', "no-stop-slow-scripts": True }, ) return response elif for_print == 3: from django.shortcuts import render_to_response response = render_to_response( 's1210_detpgtofl_infopgtoparc_listar.html', context) filename = "s1210_detpgtofl_infopgtoparc.xls" response[ 'Content-Disposition'] = 'attachment; filename=' + filename response[ 'Content-Type'] = 'application/vnd.ms-excel; charset=UTF-8' return response elif for_print == 4: from django.shortcuts import render_to_response response = render_to_response( 'tables/s1210_detpgtofl_infopgtoparc_csv.html', context) filename = "s1210_detpgtofl_infopgtoparc.csv" response[ 'Content-Disposition'] = 'attachment; filename=' + filename response['Content-Type'] = 'text/csv; charset=UTF-8' return response else: context = { 'usuario': usuario, 'modulos_permitidos_lista': modulos_permitidos_lista, 'paginas_permitidas_lista': paginas_permitidas_lista, 'permissao': permissao, 'data': datetime.datetime.now(), 'pagina': pagina, 'dict_permissoes': dict_permissoes, } return render(request, 'permissao_negada.html', context)
def index(request): return redirect('/users/%s' % request.user.username)
def assoc_access(request, plant_id, accessory_id): Plant.objects.get(id=plant_id).accessories.add(accessory_id) return redirect('detail', plant_id=plant_id)
def salvar(request, hash): db_slug = 'default' try: usuario_id = request.user.id dict_hash = get_hash_url(hash) s1210_detpgtofl_infopgtoparc_id = int(dict_hash['id']) if 'tab' not in dict_hash.keys(): dict_hash['tab'] = '' for_print = int(dict_hash['print']) except: usuario_id = False return redirect('login') usuario = get_object_or_404(Usuarios.objects.using(db_slug), excluido=False, id=usuario_id) pagina = ConfigPaginas.objects.using(db_slug).get( excluido=False, endereco='s1210_detpgtofl_infopgtoparc') permissao = ConfigPermissoes.objects.using(db_slug).get( excluido=False, config_paginas=pagina, config_perfis=usuario.config_perfis) if s1210_detpgtofl_infopgtoparc_id: s1210_detpgtofl_infopgtoparc = get_object_or_404( s1210detPgtoFlinfoPgtoParc.objects.using(db_slug), excluido=False, id=s1210_detpgtofl_infopgtoparc_id) dict_permissoes = json_to_dict(usuario.config_perfis.permissoes) paginas_permitidas_lista = usuario.config_perfis.paginas_permitidas modulos_permitidos_lista = usuario.config_perfis.modulos_permitidos dados_evento = {} dados_evento['status'] = 0 if s1210_detpgtofl_infopgtoparc_id: dados_evento = s1210_detpgtofl_infopgtoparc.evento() if dados_evento['status'] != 0: dict_permissoes['s1210_detpgtofl_infopgtoparc_apagar'] = 0 dict_permissoes['s1210_detpgtofl_infopgtoparc_editar'] = 0 if permissao.permite_visualizar: mensagem = None if s1210_detpgtofl_infopgtoparc_id: s1210_detpgtofl_infopgtoparc_form = form_s1210_detpgtofl_infopgtoparc( request.POST or None, instance=s1210_detpgtofl_infopgtoparc, slug=db_slug) else: s1210_detpgtofl_infopgtoparc_form = form_s1210_detpgtofl_infopgtoparc( request.POST or None, slug=db_slug, initial={}) if request.method == 'POST': if s1210_detpgtofl_infopgtoparc_form.is_valid(): dados = s1210_detpgtofl_infopgtoparc_form.cleaned_data import json from django.forms.models import model_to_dict if s1210_detpgtofl_infopgtoparc_id: if dados_evento['status'] == 0: dados['modificado_por_id'] = usuario_id dados['modificado_em'] = datetime.datetime.now() #s1210_detpgtofl_infopgtoparc_campos_multiple_passo1 s1210detPgtoFlinfoPgtoParc.objects.using( db_slug).filter( id=s1210_detpgtofl_infopgtoparc_id).update( **dados) obj = s1210detPgtoFlinfoPgtoParc.objects.using( db_slug).get(id=s1210_detpgtofl_infopgtoparc_id) #s1210_detpgtofl_infopgtoparc_editar_custom #s1210_detpgtofl_infopgtoparc_campos_multiple_passo2 messages.success(request, 'Alterado com sucesso!') gravar_auditoria( json.dumps( model_to_dict(s1210_detpgtofl_infopgtoparc), indent=4, sort_keys=True, default=str), json.dumps(model_to_dict(obj), indent=4, sort_keys=True, default=str), 's1210_detpgtofl_infopgtoparc', s1210_detpgtofl_infopgtoparc_id, usuario_id, 2) else: messages.error( request, 'Somente é possível alterar eventos com status "Cadastrado"!' ) else: dados['criado_por_id'] = usuario_id dados['criado_em'] = datetime.datetime.now() dados['excluido'] = False #s1210_detpgtofl_infopgtoparc_cadastrar_campos_multiple_passo1 obj = s1210detPgtoFlinfoPgtoParc(**dados) obj.save(using=db_slug) #s1210_detpgtofl_infopgtoparc_cadastrar_custom #s1210_detpgtofl_infopgtoparc_cadastrar_campos_multiple_passo2 messages.success(request, 'Cadastrado com sucesso!') gravar_auditoria( '{}', json.dumps(model_to_dict(obj), indent=4, sort_keys=True, default=str), 's1210_detpgtofl_infopgtoparc', obj.id, usuario_id, 1) if request.session['retorno_pagina'] not in ( 's1210_detpgtofl_infopgtoparc_apagar', 's1210_detpgtofl_infopgtoparc_salvar', 's1210_detpgtofl_infopgtoparc'): return redirect(request.session['retorno_pagina'], hash=request.session['retorno_hash']) if s1210_detpgtofl_infopgtoparc_id != obj.id: url_hash = base64.urlsafe_b64encode( '{"print": "0", "id": "%s"}' % (obj.id)) return redirect('s1210_detpgtofl_infopgtoparc_salvar', hash=url_hash) else: messages.error(request, 'Erro ao salvar!') s1210_detpgtofl_infopgtoparc_form = disabled_form_fields( s1210_detpgtofl_infopgtoparc_form, permissao.permite_editar) if s1210_detpgtofl_infopgtoparc_id: if dados_evento['status'] != 0: s1210_detpgtofl_infopgtoparc_form = disabled_form_fields( s1210_detpgtofl_infopgtoparc_form, 0) #s1210_detpgtofl_infopgtoparc_campos_multiple_passo3 for field in s1210_detpgtofl_infopgtoparc_form.fields.keys(): s1210_detpgtofl_infopgtoparc_form.fields[field].widget.attrs[ 'ng-model'] = 's1210_detpgtofl_infopgtoparc_' + field if int(dict_hash['print']): s1210_detpgtofl_infopgtoparc_form = disabled_form_for_print( s1210_detpgtofl_infopgtoparc_form) #[VARIAVEIS_SECUNDARIAS_VAZIAS] if s1210_detpgtofl_infopgtoparc_id: s1210_detpgtofl_infopgtoparc = get_object_or_404( s1210detPgtoFlinfoPgtoParc.objects.using(db_slug), excluido=False, id=s1210_detpgtofl_infopgtoparc_id) pass else: s1210_detpgtofl_infopgtoparc = None #s1210_detpgtofl_infopgtoparc_salvar_custom_variaveis# tabelas_secundarias = [] #[FUNCOES_ESPECIAIS_SALVAR] if dict_hash[ 'tab'] or 's1210_detpgtofl_infopgtoparc' in request.session[ 'retorno_pagina']: request.session["retorno_hash"] = hash request.session[ "retorno_pagina"] = 's1210_detpgtofl_infopgtoparc_salvar' controle_alteracoes = Auditoria.objects.using(db_slug).filter( identidade=s1210_detpgtofl_infopgtoparc_id, tabela='s1210_detpgtofl_infopgtoparc').all() context = { 'ocorrencias': dados_evento['ocorrencias'], 'validacao_precedencia': dados_evento['validacao_precedencia'], 'validacoes': dados_evento['validacoes'], 'status': dados_evento['status'], 'controle_alteracoes': controle_alteracoes, 's1210_detpgtofl_infopgtoparc': s1210_detpgtofl_infopgtoparc, 's1210_detpgtofl_infopgtoparc_form': s1210_detpgtofl_infopgtoparc_form, 'mensagem': mensagem, 's1210_detpgtofl_infopgtoparc_id': int(s1210_detpgtofl_infopgtoparc_id), 'usuario': usuario, 'hash': hash, #[VARIAVEIS_SECUNDARIAS] 'modulos_permitidos_lista': modulos_permitidos_lista, 'paginas_permitidas_lista': paginas_permitidas_lista, 'permissao': permissao, 'data': datetime.datetime.now(), 'pagina': pagina, 'dict_permissoes': dict_permissoes, 'for_print': int(dict_hash['print']), 'tabelas_secundarias': tabelas_secundarias, 'tab': dict_hash['tab'], #s1210_detpgtofl_infopgtoparc_salvar_custom_variaveis_context# } if for_print in (0, 1): return render(request, 's1210_detpgtofl_infopgtoparc_salvar.html', context) elif for_print == 2: from wkhtmltopdf.views import PDFTemplateResponse response = PDFTemplateResponse( request=request, template='s1210_detpgtofl_infopgtoparc_salvar.html', filename="s1210_detpgtofl_infopgtoparc.pdf", context=context, show_content_in_browser=True, cmd_options={ 'margin-top': 10, 'margin-bottom': 10, 'margin-right': 10, 'margin-left': 10, 'zoom': 1, 'dpi': 72, 'orientation': 'Landscape', "viewport-size": "1366 x 513", 'javascript-delay': 1000, 'footer-center': '[page]/[topage]', "no-stop-slow-scripts": True }, ) return response elif for_print == 3: from django.shortcuts import render_to_response response = render_to_response( 's1210_detpgtofl_infopgtoparc_salvar.html', context) filename = "s1210_detpgtofl_infopgtoparc.xls" response[ 'Content-Disposition'] = 'attachment; filename=' + filename response[ 'Content-Type'] = 'application/vnd.ms-excel; charset=UTF-8' return response else: context = { 'usuario': usuario, 'modulos_permitidos_lista': modulos_permitidos_lista, 'paginas_permitidas_lista': paginas_permitidas_lista, 'permissao': permissao, 'data': datetime.datetime.now(), 'pagina': pagina, 'dict_permissoes': dict_permissoes, } return render(request, 'permissao_negada.html', context)