我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.core.urlresolvers.reverse_lazy()。
def query_set(self): queryset = super().get_queryset() return queryset.filter(recipient = self.request.user) # class DeletePrivateMessage(LoginRequiredMixin,SelectRelatedMixin,generic.DeleteView): # model = PrivateMessage # select_related = ('sender','recipient') # success_url = reverse_lazy('private_messages:list') # # def get_queryset(self): # queryset = super().get_queryset() # return queryset.filter(recipient = self.request.user) # # def delete(self,*args,**kwargs): # messages.success(self.request,'Message Deleted') # return super().delete(*args,**kwargs)
def get(self, request, *args, **kwargs): """ Makes a clone within the current mission of a specified test case """ # Verify the test case passed is an int and within the path's mission id_to_clone = int(self.kwargs['pk']) passed_mission_id = int(self.kwargs['mission']) try: test_case = TestDetail.objects.get(pk=id_to_clone) except TestDetail.DoesNotExist: return HttpResponse("Test case not found.", status=404) if test_case.mission.id != passed_mission_id: return HttpResponse("Test case not linked to specified mission.", status=400) test_case.pk = None test_case.test_case_status = 'NEW' test_case.save() return HttpResponse(reverse_lazy('mission-test-edit', kwargs={'mission': test_case.mission.id, 'pk': test_case.pk}))
def post(self, request, *args, **kwargs): """Post response.""" self.form = self.get_form(self.form_class) number = request.POST['number'] name = request.POST['name'] number, modified = validate_number(number) if self.form.is_valid() or modified: if Contact.objects.filter(number=number): contact = Contact.objects.filter(number=number).first() contact.name = name contact.save() else: contact = Contact(name=name, number=number) contact.save() pk = contact.pk return redirect(reverse_lazy("contact_detail", kwargs={'pk': pk})) return self.get(request, *args, **kwargs)
def post(self, request, *args, **kwargs): """Post response.""" self.form = self.get_form(self.form_class) number = request.POST['number'] number, modified = validate_number(number) if self.form.is_valid() or modified: contact = Contact.objects.filter(id=kwargs["pk"]).first() contact.name = request.POST['name'] contact.number = number try: contact.save() except IntegrityError: return self.get(request, *args, **kwargs) pk = contact.pk return redirect(reverse_lazy("contact_detail", kwargs={'pk': pk})) return self.get(request, *args, **kwargs)
def post(self, request, *args, **kwargs): """Post response.""" self.object = None self.form = self.get_form(self.form_class) number = request.POST['number'] if len(number) > 11 or number.isalpha(): return self.get(request, *args, **kwargs) number = "+" + number if Contact.objects.filter(number=number): contact = Contact.objects.filter(number=number).first() else: contact = Contact(number=number) contact.save() pk = contact.pk return redirect(reverse_lazy('contact_detail', kwargs={'pk': pk}))
def test_complete_todo_action(self): self.login() active_todo_count = self.browser.find_element_by_id("id_todos_count").text self.assertEqual(int(active_todo_count), 2) self.browser.find_element_by_id("todo-complete-action-%s" % self.active_todo_1.id).click() self.browser.get('%s%s' % (self.live_server_url, reverse_lazy("todos:completed_list"))) user_completed_todo_count = Todo.objects.filter(user=self.user, done=True).count() todo_count_in_html_elem = self.browser.find_element_by_id("id_todos_count").text self.assertEqual(int(todo_count_in_html_elem), user_completed_todo_count) user_completed_todo = Todo.objects.filter(user=self.user, done=True).first() self.browser.find_element_by_id("todo-active-action-%s" % user_completed_todo.id).click() self.browser.get('%s%s' % (self.live_server_url, reverse_lazy("todos:active_list"))) user_active_todo_count = Todo.objects.filter(user=self.user, done=False).count() todo_count_in_html_elem = self.browser.find_element_by_id("id_todos_count").text self.assertEqual(int(todo_count_in_html_elem), user_active_todo_count)
def get(self, request, instance, redirect_url, *args, **kwargs): itens_venda = instance.itens_venda.all() pagamentos = instance.parcela_pagamento.all() instance.pk = None instance.id = None instance.status = '0' instance.save() for item in itens_venda: item.pk = None item.id = None item.save() instance.itens_venda.add(item) for pagamento in pagamentos: pagamento.pk = None pagamento.id = None pagamento.save() instance.parcela_pagamento.add(pagamento) return redirect(reverse_lazy(redirect_url, kwargs={'pk': instance.id}))
def get(self, request, instance, redirect_url, *args, **kwargs): itens_compra = instance.itens_compra.all() pagamentos = instance.parcela_pagamento.all() instance.pk = None instance.id = None instance.status = '0' instance.save() for item in itens_compra: item.pk = None item.id = None item.save() instance.itens_compra.add(item) for pagamento in pagamentos: pagamento.pk = None pagamento.id = None pagamento.save() instance.parcela_pagamento.add(pagamento) return redirect(reverse_lazy(redirect_url, kwargs={'pk': instance.id}))
def get(self, request, *args, **kwargs): nota_id = kwargs.get('pk', None) nota_obj = NotaFiscalSaida.objects.get(pk=nota_id) resp = HttpResponse(content_type='application/pdf') processador_nota = ProcessadorNotaFiscal() danfe_pdf = processador_nota.gerar_danfe(nota_obj) if processador_nota.erro: messages.error(self.request, processador_nota.message) return redirect(reverse_lazy('fiscal:editarnotafiscalsaidaview', kwargs={'pk': nota_obj.id})) else: messages.success(self.request, processador_nota.message) resp.write(danfe_pdf) return resp
def get(self, request, *args, **kwargs): nota_id = kwargs.get('pk', None) nota_obj = NotaFiscalSaida.objects.get(pk=nota_id) resp = HttpResponse(content_type='application/pdf') processador_nota = ProcessadorNotaFiscal() danfce_pdf = processador_nota.gerar_danfce(nota_obj) if processador_nota.erro: messages.error(self.request, processador_nota.message) return redirect(reverse_lazy('fiscal:editarnotafiscalsaidaview', kwargs={'pk': nota_obj.id})) else: messages.success(self.request, processador_nota.message) resp.write(danfce_pdf) return resp
def get(self, request, *args, **kwargs): if request.user.is_authenticated(): return HttpResponseRedirect(reverse_lazy('core:index')) return super(LoginView, self).get(request, *args, **kwargs)
def get_success_url(self): return reverse_lazy('student_course_detail', args=[self.course.id])
def get(self, request, *args, **kwargs): try: return super(ResultView, self).get(request, *args, **kwargs) except Http404: messages.add_message(self.request, messages.WARNING, _('Check result does not exist (anymore)')) return HttpResponseRedirect(redirect_to=reverse_lazy( 'django_datawatch_index'))
def get_success_url(self): return reverse_lazy('django_datawatch_index')
def get_success_url(self): return reverse_lazy('django_datawatch_result', kwargs=dict(pk=self.object.pk))
def get_redirect_url(self, *args, **kwargs): return reverse_lazy('django_datawatch_result', kwargs=dict(pk=self.object.pk))
def get_redirect_url(): return reverse_lazy('horizon:project:vpn:index')
def get_redirect_url(): return reverse_lazy("horizon:project:loadbalancers:index")
def get_context_data(self, **kwargs): context = super(RuleDetailsView, self).get_context_data(**kwargs) rule = self.get_data() table = fw_tabs.RulesTable(self.request) breadcrumb = [ (_("Firewalls"), reverse_lazy('horizon:project:firewalls:firewalls')), (_("Rules"), reverse_lazy('horizon:project:firewalls:rules'))] context["custom_breadcrumb"] = breadcrumb context["rule"] = rule context["url"] = self.failure_url context["actions"] = table.render_row_actions(rule) return context
def get_context_data(self, **kwargs): context = super(PolicyDetailsView, self).get_context_data(**kwargs) policy = self.get_data() table = fw_tabs.PoliciesTable(self.request) breadcrumb = [ (_("Firewalls"), reverse_lazy('horizon:project:firewalls:firewalls')), (_("Policies"), reverse_lazy('horizon:project:firewalls:policies'))] context["custom_breadcrumb"] = breadcrumb context["policy"] = policy context["url"] = self.failure_url context["actions"] = table.render_row_actions(policy) return context
def get_redirect_url(): return reverse_lazy('horizon:project:images:index')
def get_redirect_url(): return reverse_lazy('horizon:project:networks:index')
def get_data(self): try: namespace = glance.metadefs_namespace_get( self.request, self.kwargs['namespace_id'], wrap=True) except Exception: url = reverse_lazy(constants.METADATA_INDEX_URL) exceptions.handle(self.request, _('Unable to retrieve namespace details.'), redirect=url) else: return namespace
def get_redirect_url(): return reverse_lazy('horizon:admin:networks:index')
def get_absolute_url(self): target = reverse_lazy('blog:user_blog', args=[self.author.username]) return target
def get_absolute_url(self): target = reverse_lazy('blog:post_detail', args=[self.author.username, self.slug]) return target
def get_absolute_url(self): target = reverse_lazy('blog:tagged_posts_list', args=[self.slug]) return target
def password_reset(request): kwargs = { 'template_name': 'account/password_reset.html', 'success_url': reverse_lazy('account_reset_password_done'), 'email_template_name': 'account/email/password_reset_message.txt', 'subject_template_name': 'account/email/password_reset_subject.txt'} return django_views.PasswordResetView.as_view(**kwargs)(request, **kwargs)
def password_reset_confirm(request, uidb64=None, token=None): kwargs = { 'template_name': 'account/password_reset_from_key.html', 'success_url': reverse_lazy('account_reset_password_complete'), 'set_password_form': 'PasswordSetUpForm', 'token': token, 'uidb64': uidb64} return PasswordResetConfirm.as_view(**kwargs)( request, **kwargs)
def get_object(self): host_id = self.kwargs['host_id'] try: host = api.client.host_get(self.request, host_id) except Exception: msg = _("Unable to retrieve host.") redirect = reverse_lazy('horizon:admin:hosts:index') exceptions.handle(self.request, msg, redirect=redirect) return host
def get_api_next_url(self, request, cl): page_num = cl.page_num if page_num and page_num is not int or not cl.multi_page: return None info = self.model._meta.app_label, self.model._meta.model_name url = reverse_lazy("admin:%s_%s_api_list" % info) host = request.get_host() params = cl.params params["p"] = page_num + 1 return "%s://%s%s?%s" % (request.scheme, host, url, urlencode(params))
def get_api_previous_url(self, request, cl): page_num = cl.page_num if page_num == 0 or not cl.multi_page: return None info = self.model._meta.app_label, self.model._meta.model_name url = reverse_lazy("admin:%s_%s_api_list" % info) host = request.get_host() params = cl.params params["p"] = page_num - 1 return "%s://%s%s?%s" % (request.scheme, host, url, urlencode(params))
def obj_as_dict(self, request, obj): data = self.serialize_obj(obj) # serialize model instance fields datas for field in obj._meta.get_fields(): if field.is_relation and field.concrete: field_value = getattr(obj, field.name) if field_value: if field.many_to_many: data[field.name] = self.serialize_objs(field_value.all()) elif field.many_to_one or field.one_to_one or field.one_to_many: data[field.name] = self.serialize_obj(field_value) # add custom admin class field to serialized bundle model_admin_fields = self.get_model_admin_field_names(request, obj) for field in model_admin_fields: if field in data: continue if hasattr(obj, field): f = getattr(obj, field) data[field] = unicode(f) if hasattr(self, field): field_method = getattr(self, field) if callable(field_method): data[field] = field_method(obj) else: data[field] = field_method info = self.model._meta.app_label, self.model._meta.model_name admin_detail_url = str(reverse_lazy("admin:%s_%s_change" % info, args=(obj.id,))) data["admin_detail_url"] = admin_detail_url return data
def delete(self, request, *args, **kwargs): wishlist = self.get_object() if wishlist.customer == request.customer: wishlist.products.remove(self.kwargs['product_pk']) messages.success(request, _("Product removed from wishlist.")) return HttpResponseRedirect(reverse_lazy('shuup:wishlist_detail', kwargs=dict(pk=wishlist.pk))) else: raise Http404
def get_success_url(self, **kwargs): try: return reverse_lazy('list_app:item_list',kwargs={'pk':self.kwargs['pk']}) except KeyError: return reverse_lazy('list_app:list_list')
def get_success_url(self, **kwargs): return reverse_lazy('list_app:item_list',kwargs={'pk':self.kwargs['pk_list']})
def get_redirect_url(self, **kwargs): try: item = Item.objects.get(id=self.kwargs['pk']) item.completed = True item.save() return reverse_lazy('list_app:item_list',kwargs={'pk':self.kwargs['pk_list']}) except item.DoesNotExist: raise Http404
def test_register(self): """ Register a user acccount. """ response = self.client.post(reverse_lazy('list_app:new_user', kwargs={'version':'v1'}), { "username":"userapi", "password":"clave" }) self.assertEqual(response.status_code, status.HTTP_201_CREATED)
def get_absolute_url(self): return reverse_lazy('data-view', {'supportingdata': self.pk})
def process_request(self, request): try: display_interval = settings.REQUIRED_INTERSTITIAL_DISPLAY_INTERVAL except AttributeError: # Setting not defined, so assume we don't want the interstitial to display return None try: if display_interval == 0 \ and request.session['last_acknowledged_interstitial']: return None else: max_age = timedelta(hours=display_interval).total_seconds() if timegm(now().timetuple()) - request.session['last_acknowledged_interstitial'] < max_age: return None except KeyError: pass path = request.get_full_path() if re.match(str(reverse_lazy('login-interstitial')), path) or \ re.match(str(reverse_lazy('login')), path) or \ re.match(str(reverse_lazy('logout')), path) or \ re.match(settings.STATIC_URL + r'.+', path): return None return redirect('login-interstitial')
def get_context_data(self, **kwargs): """Return context for template.""" context = super(NetworksView, self).get_context_data(**kwargs) context['table'] = { 'name': 'networks', 'title': 'Peering Networks', 'api': { 'definition': reverse_lazy('networkproxy-tabledef'), 'data': reverse_lazy('networkproxy-datatable') } } return context
def get_context_data(self, **kwargs): """Return context for template.""" context = super(InternetExchangeView, self).get_context_data(**kwargs) context['table'] = { 'name': 'ixps', 'title': 'Internet Exchange Points', 'api': { 'definition': reverse_lazy('internetexchangeproxy-tabledef'), 'data': reverse_lazy('internetexchangeproxy-datatable') } } return context
def get_context_data(self, **kwargs): """Return context for template.""" context = super(PeeringSessionsView, self).get_context_data(**kwargs) context['table'] = { 'name': 'sessions', 'title': 'Peering Sessions', 'api': { 'definition': reverse_lazy('peeringsession-tabledef'), 'data': reverse_lazy('peeringsession-datatable') } } return context
def get_context_data(self, **kwargs): """Return context for template.""" context = super(PeeringRoutersView, self).get_context_data(**kwargs) context['table'] = { 'name': 'routers', 'title': 'Peering Routers', 'api': { 'definition': reverse_lazy('peeringrouter-tabledef'), 'data': reverse_lazy('peeringrouter-datatable') } } return context
def post(self, request): produto_id = request.POST.get('produto_id') produto = Produto.objects.get(id=produto_id) carrinho, _ = Carrinho.objects.get_or_create(usuario=request.user, aberto=True) carrinho.produtos.add(produto) carrinho.save() return HttpResponseRedirect(reverse_lazy('carrinho'))