Python django.core.urlresolvers.reverse_lazy() Examples

The following are 30 code examples of django.core.urlresolvers.reverse_lazy(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.urlresolvers , or try the search function .
Example #1
Source File: test_auth.py    From notes with GNU General Public License v3.0 6 votes vote down vote up
def test_request_token_with_post_method_and_access_key_and_signdata_and_no_login(self):
        url = reverse_lazy('cas_app:cas-request-token')
        serializer = TimedSerializer(self.secret_key)
        data = serializer.dumps({'redirect_to': self.redirect_to})
        data_extra = {
            'HTTP_X_SERVICES_PUBLIC_KEY': self.access_key,
        }
        response = self.client.post(url, data, content_type='application/json', **data_extra)
        response_data = serializer.loads(response.content)

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(self.cas_consumer.cas_tokens.count(), 1)
        self.assertIn('request_token', response_data)

        request_token = response_data['request_token']

        url = reverse_lazy('cas_app:cas-user-authentication')
        response = self.client.get(url, data={
            'request_token': request_token,
        })

        self.assertEqual(response.status_code, status.HTTP_302_FOUND)

        print response 
Example #2
Source File: views.py    From ideascube with GNU Affero General Public License v3.0 6 votes vote down vote up
def index(request):
    if not user_model.objects.filter(is_staff=True).exists():
        return HttpResponseRedirect(reverse_lazy('welcome_staff'))
    content = Content.objects.published().order_by('published_at').first()
    random_book = Book.objects.available().order_by('?').first()
    random_doc = Document.objects.order_by('?').first()

    staff_cards = settings.STAFF_HOME_CARDS
    builtin_cards = build_builtin_card_info()
    extra_cards = build_extra_app_card_info()
    custom_cards = settings.CUSTOM_CARDS
    package_cards = build_package_card_info()

    cards = (
        staff_cards + builtin_cards + extra_cards + custom_cards +
        package_cards)

    context = {
        'blog_content': content,
        'random_book': random_book,
        'random_doc': random_doc,
        'cards': cards,
    }
    return render(request, 'index.html', context) 
Example #3
Source File: tests.py    From longclaw with MIT License 6 votes vote down vote up
def test_post_checkout(self):
        """
        Test correctly posting to the checkout view
        """
        country = CountryFactory()
        request = RequestFactory().post(
            reverse_lazy('longclaw_checkout_view'),
            {
                'shipping-name': 'bob',
                'shipping-line_1': 'blah blah',
                'shipping-postcode': 'ytxx 23x',
                'shipping-city': 'London',
                'shipping-country': country.pk,
                'email': 'test@test.com'
            }
        )
        request.session = {}
        bid = basket_id(request)
        BasketItemFactory(basket_id=bid)
        response = CheckoutView.as_view()(request)
        self.assertEqual(response.status_code, 302) 
Example #4
Source File: question.py    From notes with GNU General Public License v3.0 6 votes vote down vote up
def post(self, request, question_pk):
        queryset = self.get_queryset()
        try:
            question = queryset.get(pk=question_pk)
        except models.Question.DoesNotExist as e:
            raise Http404(e)
        try:
            choice = question.choice_set.get(pk=request.POST['choice_pk'])
        except (KeyError, models.Choice.DoesNotExist):
            return render(request, 'polls/detail.html', {
                'question': question,
                'error_message': 'no choice selected'
            })
        else:
            choice.votes += 1
            choice.save()

            redirect_url = reverse_lazy('polls:tpl-poll-result', args=(question.pk,))
            return HttpResponseRedirect(redirect_url) 
Example #5
Source File: question.py    From notes with GNU General Public License v3.0 6 votes vote down vote up
def post(self, request, question_pk):
        queryset = self.get_queryset()
        try:
            question = queryset.get(pk=question_pk)
        except models.Question.DoesNotExist as e:
            raise Http404(e)
        try:
            choice = question.choice_set.get(pk=request.POST['choice_pk'])
        except (KeyError, models.Choice.DoesNotExist):
            return render(request, 'polls/detail.html', {
                'question': question,
                'error_message': 'no choice selected'
            })
        else:
            choice.votes += 1
            choice.save()

            redirect_url = reverse_lazy('polls:tpl-poll-result', args=(question.pk,))
            return HttpResponseRedirect(redirect_url) 
Example #6
Source File: default.py    From cadasta-platform with GNU Affero General Public License v3.0 6 votes vote down vote up
def form_valid(self, form):
        login = form.cleaned_data['login']
        user = form.user

        if (login == user.username and
                not user.phone_verified and
                not user.email_verified):
            user.is_active = False
            user.save()
            messages.add_message(
                self.request, messages.ERROR, account_inactive)
            return redirect(reverse_lazy('account:resend_token'))

        if(login == user.email and not user.email_verified or
                login == user.phone and not user.phone_verified):
            messages.add_message(
                self.request, messages.ERROR, unverified_identifier)
            return redirect(reverse_lazy('account:resend_token'))
        else:
            return super().form_valid(form) 
Example #7
Source File: views.py    From dart with Apache License 2.0 6 votes vote down vote up
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})) 
Example #8
Source File: models.py    From oxidizr with GNU General Public License v2.0 6 votes vote down vote up
def send_email(self, regenerate=False):
        if not self.verification_code or regenerate:
            self.generate_token()

        context = dict(
            verification_code=self.verification_code,
            first_name=self.owner.first_name,
            accounts_reset_password_link='http://%s%s' % (
                get_current_site().domain,
                reverse_lazy('accounts_reset_password', args=(self.id,))
            )
        )
        email(
            recipient=[self.owner.email],
            context=context,
            template_name='password_reset'
        ) 
Example #9
Source File: default.py    From cadasta-platform with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_form_kwargs(self, *args, **kwargs):
        form_kwargs = super().get_form_kwargs(*args, **kwargs)
        try:
            user_id = self.request.session['password_reset_id']
            user = User.objects.get(id=user_id)
            form_kwargs['user'] = user
        except KeyError:
            message = _(
                "You must first verify your token before resetting password."
                " Click <a href='{url}'>here</a> to get the password reset"
                " verification token. ")
            message = format_html(message.format(
                url=reverse_lazy('account:account_reset_password')))
            messages.add_message(self.request, messages.ERROR, message)

        return form_kwargs 
Example #10
Source File: test_question.py    From notes with GNU General Public License v3.0 5 votes vote down vote up
def test_index_view_with_future_question(self):
        pub_date = timezone.now() + timezone.timedelta(days=30)
        self.create_question(pub_date=pub_date)
        url = reverse_lazy('polls:tpl-poll-index')
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        self.assertIn('No polls are valiable', response.content)
        questions_pk = list(response.context['questions'].values_list('pk', flat=True))
        # future should not display
        self.assertEqual(questions_pk, []) 
Example #11
Source File: test_auth.py    From notes with GNU General Public License v3.0 5 votes vote down vote up
def test_request_token_with_get_method(self):
        url = reverse_lazy('cas_app:cas-request-token')
        response = self.client.get(url)

        self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
        self.assertEqual(models.CasToken.objects.count(), 0) 
Example #12
Source File: test_question.py    From notes with GNU General Public License v3.0 5 votes vote down vote up
def test_vote_view_with_old_question_and_selected_choice(self):
        pub_date = timezone.now() - timezone.timedelta(days=30)
        question = self.create_question(pub_date=pub_date)
        choice = question.choice_set.create(choice_text=self.faker.text(max_nb_chars=200))

        url = reverse_lazy('polls:rdr-poll-vote', kwargs={'question_pk': question.pk})
        response = self.client.post(url, {'choice_pk': choice.pk})

        self.assertEqual(response.status_code, 302)
        self.assertEqual(question.choice_set.get(pk=choice.pk).votes, 1) 
Example #13
Source File: test_question.py    From notes with GNU General Public License v3.0 5 votes vote down vote up
def test_result_view_with_future_question(self):
        pub_date = timezone.now() + timezone.timedelta(days=30)
        question = self.create_question(pub_date=pub_date)
        url = reverse_lazy('polls:tpl-poll-result', kwargs={'question_pk': question.pk})
        response = self.client.get(url)

        self.assertEqual(response.status_code, 404) 
Example #14
Source File: test_question.py    From notes with GNU General Public License v3.0 5 votes vote down vote up
def test_detail_view_with_old_question(self):
        pub_date = timezone.now() - timezone.timedelta(days=30)
        question = self.create_question(pub_date=pub_date)
        url = reverse_lazy('polls:tpl-poll-detail', kwargs={'question_pk': question.pk})
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        question_pk = response.context['question'].pk
        self.assertEqual(question_pk, question.pk) 
Example #15
Source File: test_question.py    From notes with GNU General Public License v3.0 5 votes vote down vote up
def test_detail_view_with_future_question(self):
        pub_date = timezone.now() + timezone.timedelta(days=30)
        question = self.create_question(pub_date=pub_date)
        url = reverse_lazy('polls:tpl-poll-detail', kwargs={'question_pk': question.pk})
        response = self.client.get(url)

        self.assertEqual(response.status_code, 404) 
Example #16
Source File: test_question.py    From notes with GNU General Public License v3.0 5 votes vote down vote up
def test_index_view_with_two_old_question(self):
        old_pub_date = timezone.now() - timezone.timedelta(days=30)
        old_questions = []
        old_questions.append(self.create_question(pub_date=old_pub_date))
        old_questions.append(self.create_question(pub_date=old_pub_date))
        url = reverse_lazy('polls:tpl-poll-index')
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        self.assertNotIn('No polls are valiable', response.content)
        questions_pk = list(response.context['questions'].values_list('pk', flat=True))
        self.assertEqual(questions_pk, map(lambda p: p.pk, old_questions)) 
Example #17
Source File: test_question.py    From notes with GNU General Public License v3.0 5 votes vote down vote up
def test_vote_view_with_future_question_and_selected_choice(self):
        pub_date = timezone.now() + timezone.timedelta(days=30)
        question = self.create_question(pub_date=pub_date)
        choice = question.choice_set.create(choice_text=self.faker.text(max_nb_chars=200))

        url = reverse_lazy('polls:rdr-poll-vote', kwargs={'question_pk': question.pk})
        response = self.client.post(url, {'choice_pk': choice.pk})

        self.assertEqual(response.status_code, 404) 
Example #18
Source File: views.py    From django-unifi-portal with MIT License 5 votes vote down vote up
def form_valid(self, form):

        # Get the request url from unifi
        try:
            self.success_url = self.request.session['mynext']
        except:
            self.success_url = reverse_lazy('index') #to test!

        user = form.save(commit=False)
        user.set_password(form.cleaned_data['password'])
        user.username = form.cleaned_data['username'].lower()
        user.email = form.cleaned_data['username'].lower()   #ATTENZIONE: maschero la username con la email
        user.first_name = form.cleaned_data['first_name'].lower()
        user.last_name = form.cleaned_data['last_name'].lower()
        user.is_active = True
        user.save()

        unifi_user = UnifiUser()
        unifi_user.user = user
        unifi_user.phone = form.cleaned_data['phone']
        unifi_user.gender = form.cleaned_data['gender']
        unifi_user.save()

        # execute login
        user_logged = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
        login(self.request, user_logged)

        return HttpResponseRedirect(self.get_success_url()) 
Example #19
Source File: test_question.py    From notes with GNU General Public License v3.0 5 votes vote down vote up
def test_index_view_with_future_and_old_question(self):
        future_pub_date = timezone.now() + timezone.timedelta(days=30)
        self.create_question(pub_date=future_pub_date)
        old_pub_date = timezone.now() - timezone.timedelta(days=30)
        old_question = self.create_question(pub_date=old_pub_date)
        url = reverse_lazy('polls:tpl-poll-index')
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        self.assertNotIn('No polls are valiable', response.content)
        questions_pk = list(response.context['questions'].values_list('pk', flat=True))
        self.assertEqual(questions_pk, [old_question.pk]) 
Example #20
Source File: test_question.py    From notes with GNU General Public License v3.0 5 votes vote down vote up
def test_index_view_with_old_question(self):
        pub_date = timezone.now() - timezone.timedelta(days=30)
        question = self.create_question(pub_date=pub_date)
        url = reverse_lazy('polls:tpl-poll-index')
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        self.assertNotIn('No polls are valiable', response.content)
        questions_pk = list(response.context['questions'].values_list('pk', flat=True))
        self.assertEqual(questions_pk, [question.pk]) 
Example #21
Source File: views.py    From acacia_main with MIT License 5 votes vote down vote up
def get_success_url(self):
        return str(reverse_lazy('user_sessions:session_list')) 
Example #22
Source File: views.py    From django-admino with MIT License 5 votes vote down vote up
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)) 
Example #23
Source File: test_question.py    From notes with GNU General Public License v3.0 5 votes vote down vote up
def test_index_view_with_no_question(self):
        url = reverse_lazy('polls:tpl-poll-index')
        response = self.client.get(url)

        self.assertEqual(response.status_code, 200)
        self.assertIn('No polls are valiable', response.content)
        questions_pk = list(response.context['questions'].values_list('pk', flat=True))
        self.assertEqual(questions_pk, []) 
Example #24
Source File: views.py    From codesy with GNU Affero General Public License v3.0 5 votes vote down vote up
def reverse_lazy_with_param(self, template_name):
        request_dict = self.request.GET or self.request.POST
        return_param = urllib.urlencode(request_dict)
        return '%s?%s' % (reverse_lazy(template_name), return_param) 
Example #25
Source File: decorators.py    From osler with GNU General Public License v3.0 5 votes vote down vote up
def clintype_required(func):
    return session_passes_test(clintype_set, fail_url=reverse_lazy('choose-clintype'))(func) 
Example #26
Source File: views.py    From Python-Journey-from-Novice-to-Expert with MIT License 5 votes vote down vote up
def form_valid(self, form):
        self.success_url = reverse_lazy(
            'records:edit',
            kwargs={'pk': self.object.pk}
        )
        return super(RecordUpdateView, self).form_valid(form) 
Example #27
Source File: decorators.py    From osler with GNU General Public License v3.0 5 votes vote down vote up
def provider_update_required(func):
    return user_passes_test(provider_has_updated, login_url=reverse_lazy('provider-update'))(func) 
Example #28
Source File: decorators.py    From osler with GNU General Public License v3.0 5 votes vote down vote up
def provider_required(func):
    return user_passes_test(provider_exists, login_url=reverse_lazy('new-provider'))(func) 
Example #29
Source File: views.py    From acacia_main with MIT License 5 votes vote down vote up
def get_success_url(self):
        return str(reverse_lazy('user_sessions:session_list')) 
Example #30
Source File: default.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def form_valid(self, form):
        try:
            with transaction.atomic():
                phone = form.data.get('phone')
                messages.add_message(
                    self.request, messages.SUCCESS,
                    _("Successfully updated profile information"))

                if (phone != self.instance_phone and phone):
                    message = _("Verification Token sent to {phone}")
                    message = message.format(phone=phone)
                    messages.add_message(self.request, messages.INFO, message)
                    self.request.session['phone_verify_id'] = self.object.id
                    self.success_url = reverse_lazy('account:verify_phone')

                return super().form_valid(form)
        except TwilioRestException as e:
            if e.status >= 500:
                logger.exception(str(e))
                msg = TWILIO_ERRORS.get('default')
            else:
                msg = TWILIO_ERRORS.get(e.code)

            if msg:
                form.add_error('phone', msg)
                return self.form_invalid(form)
            else:
                raise