Python django.core.urlresolvers.reverse() Examples

The following are code examples for showing how to use django.core.urlresolvers.reverse(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: noke-platform   Author: NokeCodes   File: views.py    MIT License 8 votes vote down vote up
def join(request, slug):
    """Toggles whether user has an active membership in the project while maintaining the membership type."""
    if request.method == 'POST' and request.user.is_authenticated() and request.user.is_active:
        project = get_object_or_404(Project, slug=slug)
        action = request.POST.get('action')
        if action == 'unjoin':
            try:
                membership = Membership.objects.get(user=request.user, project=project)
                membership.is_active = False
                membership.save()
            except Membership.DoesNotExist:
                pass
        elif action == 'join':
            membership, _ = Membership.objects.update_or_create(user=request.user, project=project,
                                                                defaults={'is_active': True})

    return HttpResponseRedirect(reverse('projects:details', args=(slug,))) 
Example 2
Project: django-xadmin   Author: MarkHoo   File: dashboard.py    MIT License 6 votes vote down vote up
def context(self, context):
        btns = []
        for b in self.q_btns:
            btn = {}
            if 'model' in b:
                model = self.get_model(b['model'])
                if not self.user.has_perm("%s.view_%s" % (model._meta.app_label, model._meta.model_name)):
                    continue
                btn['url'] = reverse("%s:%s_%s_%s" % (self.admin_site.app_name, model._meta.app_label,
                                                      model._meta.model_name, b.get('view', 'changelist')))
                btn['title'] = model._meta.verbose_name
                btn['icon'] = self.dashboard.get_model_icon(model)
            else:
                try:
                    btn['url'] = reverse(b['url'])
                except NoReverseMatch:
                    btn['url'] = b['url']

            if 'title' in b:
                btn['title'] = b['title']
            if 'icon' in b:
                btn['icon'] = b['icon']
            btns.append(btn)

        context.update({'btns': btns}) 
Example 3
Project: django-xadmin   Author: MarkHoo   File: topnav.py    MIT License 6 votes vote down vote up
def block_top_navbar(self, context, nodes):
        search_models = []

        site_name = self.admin_site.name
        if self.global_search_models == None:
            models = self.admin_site._registry.keys()
        else:
            models = self.global_search_models

        for model in models:
            app_label = model._meta.app_label

            if self.has_model_perm(model, "view"):
                info = (app_label, model._meta.model_name)
                if getattr(self.admin_site._registry[model], 'search_fields', None):
                    try:
                        search_models.append({
                            'title': _('Search %s') % capfirst(model._meta.verbose_name_plural),
                            'url': reverse('xadmin:%s_%s_changelist' % info, current_app=site_name),
                            'model': model
                        })
                    except NoReverseMatch:
                        pass
        return nodes.append(loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'search_models': search_models, 'search_name': SEARCH_VAR})) 
Example 4
Project: django-xadmin   Author: MarkHoo   File: topnav.py    MIT License 6 votes vote down vote up
def block_top_navmenu(self, context, nodes):
        add_models = []

        site_name = self.admin_site.name

        if self.global_add_models == None:
            models = self.admin_site._registry.keys()
        else:
            models = self.global_add_models
        for model in models:
            app_label = model._meta.app_label

            if self.has_model_perm(model, "add"):
                info = (app_label, model._meta.model_name)
                try:
                    add_models.append({
                        'title': _('Add %s') % capfirst(model._meta.verbose_name),
                        'url': reverse('xadmin:%s_%s_add' % info, current_app=site_name),
                        'model': model
                    })
                except NoReverseMatch:
                    pass

        nodes.append(
            loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'add_models': add_models})) 
Example 5
Project: django-xadmin   Author: MarkHoo   File: relate.py    MIT License 6 votes vote down vote up
def _get_all_related_objects(self, local_only=False, include_hidden=False,
                                 include_proxy_eq=False):
        """
        Returns a list of related fields (also many to many)
        :param local_only:
        :param include_hidden:
        :return: list
        """
        include_parents = True if local_only is False else PROXY_PARENTS
        fields = self.opts._get_fields(
            forward=False, reverse=True,
            include_parents=include_parents,
            include_hidden=include_hidden
        )
        if include_proxy_eq:
            children = chain.from_iterable(c._relation_tree
                                           for c in self.opts.concrete_model._meta.proxied_children
                                           if c is not self.opts)
            relations = (f.remote_field for f in children
                         if include_hidden or not f.remote_field.field.remote_field.is_hidden())
            fields = chain(fields, relations)
        return list(fields) 
Example 6
Project: django-xadmin   Author: MarkHoo   File: dashboard.py    MIT License 6 votes vote down vote up
def context(self, context):
        btns = []
        for b in self.q_btns:
            btn = {}
            if 'model' in b:
                model = self.get_model(b['model'])
                if not self.user.has_perm("%s.view_%s" % (model._meta.app_label, model._meta.model_name)):
                    continue
                btn['url'] = reverse("%s:%s_%s_%s" % (self.admin_site.app_name, model._meta.app_label,
                                                      model._meta.model_name, b.get('view', 'changelist')))
                btn['title'] = model._meta.verbose_name
                btn['icon'] = self.dashboard.get_model_icon(model)
            else:
                try:
                    btn['url'] = reverse(b['url'])
                except NoReverseMatch:
                    btn['url'] = b['url']

            if 'title' in b:
                btn['title'] = b['title']
            if 'icon' in b:
                btn['icon'] = b['icon']
            btns.append(btn)

        context.update({'btns': btns}) 
Example 7
Project: django-xadmin   Author: MarkHoo   File: topnav.py    MIT License 6 votes vote down vote up
def block_top_navbar(self, context, nodes):
        search_models = []

        site_name = self.admin_site.name
        if self.global_search_models == None:
            models = self.admin_site._registry.keys()
        else:
            models = self.global_search_models

        for model in models:
            app_label = model._meta.app_label

            if self.has_model_perm(model, "view"):
                info = (app_label, model._meta.model_name)
                if getattr(self.admin_site._registry[model], 'search_fields', None):
                    try:
                        search_models.append({
                            'title': _('Search %s') % capfirst(model._meta.verbose_name_plural),
                            'url': reverse('xadmin:%s_%s_changelist' % info, current_app=site_name),
                            'model': model
                        })
                    except NoReverseMatch:
                        pass
        return nodes.append(loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'search_models': search_models, 'search_name': SEARCH_VAR})) 
Example 8
Project: django-xadmin   Author: MarkHoo   File: topnav.py    MIT License 6 votes vote down vote up
def block_top_navmenu(self, context, nodes):
        add_models = []

        site_name = self.admin_site.name

        if self.global_add_models == None:
            models = self.admin_site._registry.keys()
        else:
            models = self.global_add_models
        for model in models:
            app_label = model._meta.app_label

            if self.has_model_perm(model, "add"):
                info = (app_label, model._meta.model_name)
                try:
                    add_models.append({
                        'title': _('Add %s') % capfirst(model._meta.verbose_name),
                        'url': reverse('xadmin:%s_%s_add' % info, current_app=site_name),
                        'model': model
                    })
                except NoReverseMatch:
                    pass

        nodes.append(
            loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'add_models': add_models})) 
Example 9
Project: django-xadmin   Author: MarkHoo   File: relate.py    MIT License 6 votes vote down vote up
def _get_all_related_objects(self, local_only=False, include_hidden=False,
                                 include_proxy_eq=False):
        """
        Returns a list of related fields (also many to many)
        :param local_only:
        :param include_hidden:
        :return: list
        """
        include_parents = True if local_only is False else PROXY_PARENTS
        fields = self.opts._get_fields(
            forward=False, reverse=True,
            include_parents=include_parents,
            include_hidden=include_hidden
        )
        if include_proxy_eq:
            children = chain.from_iterable(c._relation_tree
                                           for c in self.opts.concrete_model._meta.proxied_children
                                           if c is not self.opts)
            relations = (f.remote_field for f in children
                         if include_hidden or not f.remote_field.field.remote_field.is_hidden())
            fields = chain(fields, relations)
        return list(fields) 
Example 10
Project: noke-platform   Author: NokeCodes   File: views.py    MIT License 6 votes vote down vote up
def signup(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('users:profile', args=(request.user.get_username(),)))
    if request.method == 'POST':
        user_form = NewUserForm(request.POST)
        if user_form.is_valid():
            user_form.save()
            user = authenticate(username=user_form.cleaned_data.get('username'),
                                password=user_form.cleaned_data.get('password1'))
            login(request, user)
            return HttpResponseRedirect(reverse('users:edit_profile', args=(user.get_username(),)))
    else:
        user_form = NewUserForm()
    return render(request, 'registration/signup.html', {
        'user_form': user_form,
    }) 
Example 11
Project: noke-platform   Author: NokeCodes   File: views.py    MIT License 6 votes vote down vote up
def edit_profile(request, username):
    if request.user.get_username() != username:
        # Can only edit your own profile.
        return HttpResponseRedirect(reverse('users:profile', args=(username,)))

    user = User.objects.select_related('profile').get(username=username)

    if request.method == 'POST':
        user_form = UserForm(request.POST, request.FILES, instance=user)
        profile_form = UserProfileForm(request.POST, request.FILES, instance=user.profile)

        if all((user_form.is_valid(), profile_form.is_valid())):
            user_form.save()
            profile_form.save()
            return HttpResponseRedirect(reverse('users:profile', args=(username,)))
    else:
        user_form = UserForm(instance=user)
        profile_form = UserProfileForm(instance=user.profile)

    return render(request, 'users/edit_profile.html', {
        'user_form': user_form,
        'profile_form': profile_form,
    }) 
Example 12
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_registration_view_failure(self):
        """
        A ``POST`` to the ``register`` view with invalid data does not
        create a user, and displays appropriate error messages.

        """
        response = self.client.post(reverse('registration_register'),
                                    data={'username': 'bob',
                                          'email': '[email protected]',
                                          'password1': 'foo',
                                          'password2': 'bar'})
        self.assertEqual(response.status_code, 200)
        self.failIf(response.context['form'].is_valid())
        self.assertFormError(response, 'form', field=None,
                             errors=u"The two password fields didn't match.")
        self.assertEqual(len(mail.outbox), 0) 
Example 13
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_registration_view_closed(self):
        """
        Any attempt to access the ``register`` view when registration
        is closed fails and redirects.

        """
        old_allowed = getattr(settings, 'REGISTRATION_OPEN', True)
        settings.REGISTRATION_OPEN = False

        closed_redirect = 'http://testserver%s' % reverse('registration_disallowed')

        response = self.client.get(reverse('registration_register'))
        self.assertRedirects(response, closed_redirect)

        # Even if valid data is posted, it still shouldn't work.
        response = self.client.post(reverse('registration_register'),
                                    data={'username': 'alice',
                                          'email': '[email protected]',
                                          'password1': 'swordfish',
                                          'password2': 'swordfish'})
        self.assertRedirects(response, closed_redirect)
        self.assertEqual(RegistrationProfile.objects.count(), 0)

        settings.REGISTRATION_OPEN = old_allowed 
Example 14
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_valid_activation(self):
        """
        Test that the ``activate`` view properly handles a valid
        activation (in this case, based on the default backend's
        activation window).

        """
        success_redirect = 'http://testserver%s' % reverse('registration_activation_complete')
        
        # First, register an account.
        self.client.post(reverse('registration_register'),
                         data={'username': 'alice',
                               'email': '[email protected]',
                               'password1': 'swordfish',
                               'password2': 'swordfish'})
        profile = RegistrationProfile.objects.get(user__username='alice')
        response = self.client.get(reverse('registration_activate',
                                           kwargs={'activation_key': profile.activation_key}))
        self.assertRedirects(response, success_redirect)
        self.failUnless(User.objects.get(username='alice').is_active) 
Example 15
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_invalid_activation(self):
        """
        Test that the ``activate`` view properly handles an invalid
        activation (in this case, based on the default backend's
        activation window).

        """
        # Register an account and reset its date_joined to be outside
        # the activation window.
        self.client.post(reverse('registration_register'),
                         data={'username': 'bob',
                               'email': '[email protected]',
                               'password1': 'secret',
                               'password2': 'secret'})
        expired_user = User.objects.get(username='bob')
        expired_user.date_joined = expired_user.date_joined - datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
        expired_user.save()

        expired_profile = RegistrationProfile.objects.get(user=expired_user)
        response = self.client.get(reverse('registration_activate',
                                           kwargs={'activation_key': expired_profile.activation_key}))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['activation_key'],
                         expired_profile.activation_key)
        self.failIf(User.objects.get(username='bob').is_active) 
Example 16
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_activation_success_url(self):
        """
        Passing ``success_url`` to the ``activate`` view and
        successfully activating will result in that URL being used for
        the redirect.
        
        """
        success_redirect = 'http://testserver%s' % reverse('registration_test_custom_success_url')
        self.client.post(reverse('registration_register'),
                         data={'username': 'alice',
                               'email': '[email protected]',
                               'password1': 'swordfish',
                               'password2': 'swordfish'})
        profile = RegistrationProfile.objects.get(user__username='alice')
        response = self.client.get(reverse('registration_test_activate_success_url',
                                           kwargs={'activation_key': profile.activation_key}))
        self.assertRedirects(response, success_redirect) 
Example 17
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_registration_view_failure(self):
        """
        A ``POST`` to the ``register`` view with invalid data does not
        create a user, and displays appropriate error messages.

        """
        response = self.client.post(reverse('registration_register'),
                                    data={'username': 'bob',
                                          'email': '[email protected]',
                                          'password1': 'foo',
                                          'password2': 'bar'})
        self.assertEqual(response.status_code, 200)
        self.failIf(response.context['form'].is_valid())
        self.assertFormError(response, 'form', field=None,
                             errors=u"The two password fields didn't match.")
        self.assertEqual(len(mail.outbox), 0) 
Example 18
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_registration_view_closed(self):
        """
        Any attempt to access the ``register`` view when registration
        is closed fails and redirects.

        """
        old_allowed = getattr(settings, 'REGISTRATION_OPEN', True)
        settings.REGISTRATION_OPEN = False

        closed_redirect = 'http://testserver%s' % reverse('registration_disallowed')

        response = self.client.get(reverse('registration_register'))
        self.assertRedirects(response, closed_redirect)

        # Even if valid data is posted, it still shouldn't work.
        response = self.client.post(reverse('registration_register'),
                                    data={'username': 'alice',
                                          'email': '[email protected]',
                                          'password1': 'swordfish',
                                          'password2': 'swordfish'})
        self.assertRedirects(response, closed_redirect)
        self.assertEqual(RegistrationProfile.objects.count(), 0)

        settings.REGISTRATION_OPEN = old_allowed 
Example 19
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_valid_activation(self):
        """
        Test that the ``activate`` view properly handles a valid
        activation (in this case, based on the default backend's
        activation window).

        """
        success_redirect = 'http://testserver%s' % reverse('registration_activation_complete')
        
        # First, register an account.
        self.client.post(reverse('registration_register'),
                         data={'username': 'alice',
                               'email': '[email protected]',
                               'password1': 'swordfish',
                               'password2': 'swordfish'})
        profile = RegistrationProfile.objects.get(user__username='alice')
        response = self.client.get(reverse('registration_activate',
                                           kwargs={'activation_key': profile.activation_key}))
        self.assertRedirects(response, success_redirect)
        self.failUnless(User.objects.get(username='alice').is_active) 
Example 20
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_invalid_activation(self):
        """
        Test that the ``activate`` view properly handles an invalid
        activation (in this case, based on the default backend's
        activation window).

        """
        # Register an account and reset its date_joined to be outside
        # the activation window.
        self.client.post(reverse('registration_register'),
                         data={'username': 'bob',
                               'email': '[email protected]',
                               'password1': 'secret',
                               'password2': 'secret'})
        expired_user = User.objects.get(username='bob')
        expired_user.date_joined = expired_user.date_joined - datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
        expired_user.save()

        expired_profile = RegistrationProfile.objects.get(user=expired_user)
        response = self.client.get(reverse('registration_activate',
                                           kwargs={'activation_key': expired_profile.activation_key}))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['activation_key'],
                         expired_profile.activation_key)
        self.failIf(User.objects.get(username='bob').is_active) 
Example 21
Project: django-reading-list   Author: simonv3   File: tests.py    MIT License 6 votes vote down vote up
def test_create_book_succeeds(self):
        """
        Ensure we can create a new book object.
        """
        url = reverse('book-list')
        data = {
            'title': 'A Test Book Title',
            'sub_title': 'A Test Book Title',
            'isbn_13': '0123456789123',
            'published': datetime.date.today(),
            'authors': [self.author.id],
            'publisher': self.publisher.id
            }
        response = self.client.post(url, data, format='json')

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(response.data['title'], data['title'])
        self.assertEqual(Book.objects.all().first().title, data['title']) 
Example 22
Project: django-reading-list   Author: simonv3   File: tests.py    MIT License 6 votes vote down vote up
def test_delete_book_succeeds(self):
        """
        Ensure we can delete a book object.
        """

        data = {
            'title': 'A Test Book Title',
            'sub_title': 'A Test Book Title',
            'isbn_13': '0123456789123',
            'published': datetime.date.today(),
            'publisher': self.publisher
        }

        book = Book.objects.create(**data)
        book.authors.add(self.author)

        url = reverse('book-detail', args=(book.id,))
        response = self.client.delete(url)

        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) 
Example 23
Project: django-reading-list   Author: simonv3   File: tests.py    MIT License 6 votes vote down vote up
def test_partial_update_book_succeeds(self):
        """
        Ensure we can update a book object.
        """

        data = {
            'title': 'Updated Title',
            'sub_title': 'A Test Book Title',
            'isbn_13': '0123456789123',
            'published': datetime.date.today(),
            'publisher': self.publisher
        }

        book = Book.objects.create(**data)
        book.authors.add(self.author)

        url = reverse('book-detail', args=(book.id,))
        response = self.client.patch(url, {'title': 'Patched Title',
                                           'sub_title': 'New'})

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

        self.assertEqual(Book.objects.all().first().title, 'Patched Title')
        self.assertEqual(Book.objects.all().first().sub_title, 'New') 
Example 24
Project: django-reading-list   Author: simonv3   File: tests.py    MIT License 6 votes vote down vote up
def test_update_book_succeeds(self):
        """
        Ensure we can update a book object.
        """

        data = {
            'title': 'Updated Title',
            'sub_title': 'A Test Book Title',
            'isbn_13': '0123456789123',
            'published': datetime.date.today(),
            'publisher': self.publisher
        }

        book = Book.objects.create(**data)
        book.authors.add(self.author)
        new_publisher = Publisher.objects.create(name='Heyo')
        url = reverse('book-detail', args=(book.id,))
        response = self.client.put(url, {'title': 'Updated Title'
                                         'sub_title': 'New Sub',
                                         'isbn_13': '1234567891234',
                                         'publisher': new_publisher,
                                         'published': datetime.date.today()}) 
Example 25
Project: django-reading-list   Author: simonv3   File: tests.py    MIT License 6 votes vote down vote up
def test_create_book_succeeds(self):
        """
        Ensure we can create a new book object.
        """
        url = reverse('book-list')
        data = {
            'title': 'A Test Book Title',
            'sub_title': 'A Test Book Title',
            'isbn_13': '0123456789123',
            'published': datetime.date.today(),
            'authors': [self.author.id],
            'publisher': self.publisher.id
            }
        response = self.client.post(url, data, format='json')

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(response.data['title'], data['title'])
        self.assertEqual(Book.objects.all().first().title, data['title']) 
Example 26
Project: VisualNN   Author: angelhunt   File: test_views.py    GNU General Public License v3.0 6 votes vote down vote up
def test_caffe_import(self):
        sample_file = open(os.path.join(settings.BASE_DIR,
                                        'example/caffe',
                                        'GoogleNet.prototxt'), 'r')
        # Test 1
        response = self.client.post(reverse('caffe-import'),
                                    {'file': sample_file})
        response = json.loads(response.content)
        self.assertEqual(response['result'], 'success')
        # Test 2
        sample_file = open(os.path.join(settings.BASE_DIR,
                                        'example/keras',
                                        'vgg16.json'), 'r')
        response = self.client.post(reverse('caffe-import'),
                                    {'file': sample_file})
        response = json.loads(response.content)
        self.assertEqual(response['result'], 'error')
        self.assertEqual(response['error'], 'Invalid Prototxt\n'
                                            'local variable \'prototxt\' referenced before assignment') 
Example 27
Project: VisualNN   Author: angelhunt   File: test_views.py    GNU General Public License v3.0 6 votes vote down vote up
def test_caffe_import_by_input(self):
        sample_file = open(os.path.join(settings.BASE_DIR,
                                        'example/caffe',
                                        'GoogleNet.prototxt'), 'r')
        # Test 1
        response = self.client.post(reverse('caffe-import'),
                                    {'config': sample_file.read()})
        response = json.loads(response.content)
        self.assertEqual(response['result'], 'success')
        # Test 2
        sample_file = open(os.path.join(settings.BASE_DIR,
                                        'example/keras',
                                        'vgg16.json'), 'r')
        response = self.client.post(reverse('caffe-import'),
                                    {'config': sample_file.read()})
        response = json.loads(response.content)
        self.assertEqual(response['result'], 'error')
        self.assertEqual(response['error'], 'Invalid Prototxt\n'
                                            '1:1 : Expected identifier or number, got {.') 
Example 28
Project: VisualNN   Author: angelhunt   File: test_views.py    GNU General Public License v3.0 6 votes vote down vote up
def test_caffe_import(self):
        # Test 1
        top = L.Convolution(kernel_size=3, pad=1, stride=1, num_output=128,
                            weight_filler={'type': 'xavier'}, bias_filler={'type': 'constant'})
        with open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'w') as f:
            f.write(str(to_proto(top)))
        sample_file = open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'r')
        response = self.client.post(reverse('caffe-import'), {'file': sample_file})
        response = json.loads(response.content)
        os.remove(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'))
        self.assertGreaterEqual(len(response['net']['l0']['params']), 6)
        self.assertEqual(response['result'], 'success')
        # Test 2
        top = L.Convolution(kernel_w=3, kernel_h=3, pad_w=1, pad_h=1, stride=1, num_output=128,
                            weight_filler={'type': 'xavier'}, bias_filler={'type': 'constant'})
        with open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'w') as f:
            f.write(str(to_proto(top)))
        sample_file = open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'r')
        response = self.client.post(reverse('caffe-import'), {'file': sample_file})
        response = json.loads(response.content)
        os.remove(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'))
        self.assertGreaterEqual(len(response['net']['l0']['params']), 6)
        self.assertEqual(response['result'], 'success') 
Example 29
Project: VisualNN   Author: angelhunt   File: test_views.py    GNU General Public License v3.0 6 votes vote down vote up
def test_caffe_import(self):
        # Test 1
        top = L.Pooling(kernel_size=2, pad=0, stride=2, pool=1)
        with open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'w') as f:
            f.write(str(to_proto(top)))
        sample_file = open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'r')
        response = self.client.post(reverse('caffe-import'), {'file': sample_file})
        response = json.loads(response.content)
        os.remove(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'))
        self.assertGreaterEqual(len(response['net']['l0']['params']), 4)
        self.assertEqual(response['result'], 'success')
        # Test 2
        top = L.Pooling(kernel_size=2, pad=0, stride=2, pool=2)
        with open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'w') as f:
            f.write(str(to_proto(top)))
        sample_file = open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'r')
        response = self.client.post(reverse('caffe-import'), {'file': sample_file})
        response = json.loads(response.content)
        os.remove(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'))
        self.assertGreaterEqual(len(response['net']['l0']['params']), 4)
        self.assertEqual(response['result'], 'success') 
Example 30
Project: mpesaviz   Author: savioabuga   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def form_valid(self, form):
            file_type = form.cleaned_data.get('type')
            self.update_records(self.request.FILES['file'], file_type)
            return redirect(reverse('transactions.transaction_list')) 
Example 31
Project: autolims   Author: scottbecker   File: views.py    MIT License 5 votes vote down vote up
def dispatch(self, request):
        
        #get the users 
        
        organization_query = Organization.objects.filter(users=self.request.user)
        
        if not organization_query.exists():
            messages.add_message(self.request, messages.WARNING, 
                                 'User doesn\'t have any organizations')
            return redirect('%s?next=%s' % (settings.LOGIN_URL, self.request.path))            
        
        organization = organization_query.first()
        
        return redirect(reverse('projects', 
                                kwargs={'organization_subdomain':organization.subdomain})) 
Example 32
Project: django-feedaggregator   Author: fasouto   File: feeds.py    MIT License 5 votes vote down vote up
def link(self):
        return reverse("feedaggregator:rss_latest_items") 
Example 33
Project: django-feedaggregator   Author: fasouto   File: models.py    MIT License 5 votes vote down vote up
def get_absolute_url(self):
        return reverse('feedaggregator:feed_detail', args=[self.slug]) 
Example 34
Project: django-feedaggregator   Author: fasouto   File: models.py    MIT License 5 votes vote down vote up
def get_absolute_url(self):
        return reverse('feedaggregator:item_detail', kwargs={"slug": self.slug}) 
Example 35
Project: django-feedaggregator   Author: fasouto   File: test_views.py    MIT License 5 votes vote down vote up
def test_export_opml(self):
        """Export all the active feeds as OPML"""
        response = self.client.get(reverse('feedaggregator:opml'))
        self.assertEqual(response.content, self.opml_example) 
Example 36
Project: django-feedaggregator   Author: fasouto   File: test_views.py    MIT License 5 votes vote down vote up
def test_index(self):
        response = self.client.get(reverse('feedaggregator:item_list'))
        self.assertEqual(response.status_code, 200) 
        self.assertTrue('item_list' in response.context) 
Example 37
Project: django-feedaggregator   Author: fasouto   File: test_views.py    MIT License 5 votes vote down vote up
def test_feed_detail(self):
        response = self.client.get(reverse('feedaggregator:feed_detail', kwargs={'slug': self.test_feed.slug}))
        self.assertEqual(response.status_code, 200)
        self.assertTrue('item_list' in response.context)

        response = self.client.get(reverse('feedaggregator:item_detail', kwargs={'slug': "Foo"}))
        self.assertEqual(response.status_code, 404) 
Example 38
Project: django-feedaggregator   Author: fasouto   File: test_views.py    MIT License 5 votes vote down vote up
def test_rss(self):
        response = self.client.get(reverse('feedaggregator:rss_latest_items'))
        self.assertEqual(response.status_code, 200) 
Example 39
Project: django-feedaggregator   Author: fasouto   File: test_views.py    MIT License 5 votes vote down vote up
def test_atom(self):
        response = self.client.get(reverse('feedaggregator:atom_latest_items'))
        self.assertEqual(response.status_code, 200) 
Example 40
Project: django-xadmin   Author: MarkHoo   File: dashboard.py    MIT License 5 votes vote down vote up
def model_admin_url(self, name, *args, **kwargs):
        return reverse(
            "%s:%s_%s_%s" % (self.admin_site.app_name, self.app_label,
                             self.model_name, name), args=args, kwargs=kwargs) 
Example 41
Project: django-xadmin   Author: MarkHoo   File: base.py    MIT License 5 votes vote down vote up
def get_admin_url(self, name, *args, **kwargs):
        return reverse('%s:%s' % (self.admin_site.app_name, name), args=args, kwargs=kwargs) 
Example 42
Project: django-xadmin   Author: MarkHoo   File: base.py    MIT License 5 votes vote down vote up
def get_model_url(self, model, name, *args, **kwargs):
        return reverse(
            '%s:%s_%s_%s' % (self.admin_site.app_name, model._meta.app_label,
                             model._meta.model_name, name),
            args=args, kwargs=kwargs, current_app=self.admin_site.name) 
Example 43
Project: django-xadmin   Author: MarkHoo   File: base.py    MIT License 5 votes vote down vote up
def model_admin_url(self, name, *args, **kwargs):
        return reverse(
            "%s:%s_%s_%s" % (self.admin_site.app_name, self.opts.app_label,
            self.model_name, name), args=args, kwargs=kwargs) 
Example 44
Project: django-xadmin   Author: MarkHoo   File: relate.py    MIT License 5 votes vote down vote up
def related_link(self, instance):
        links = []
        for rel, view_perm, add_perm in self.get_related_list():
            opts = rel.related_model._meta

            label = opts.app_label
            model_name = opts.model_name

            field = rel.field
            rel_name = rel.get_related_field().name

            verbose_name = force_text(opts.verbose_name)
            lookup_name = '%s__%s__exact' % (field.name, rel_name)

            link = ''.join(('<li class="with_menu_btn">',

                            '<a href="%s?%s=%s" title="%s"><i class="icon fa fa-th-list"></i> %s</a>' %
                          (
                            reverse('%s:%s_%s_changelist' % (
                                    self.admin_site.app_name, label, model_name)),
                            RELATE_PREFIX + lookup_name, str(instance.pk), verbose_name, verbose_name) if view_perm else
                            '<a><span class="text-muted"><i class="icon fa fa-blank"></i> %s</span></a>' % verbose_name,

                            '<a class="add_link dropdown-menu-btn" href="%s?%s=%s"><i class="icon fa fa-plus pull-right"></i></a>' %
                          (
                            reverse('%s:%s_%s_add' % (
                                    self.admin_site.app_name, label, model_name)),
                            RELATE_PREFIX + lookup_name, str(
                instance.pk)) if add_perm else "",

                '</li>'))
            links.append(link)
        ul_html = '<ul class="dropdown-menu" role="menu">%s</ul>' % ''.join(
            links)
        return '<div class="dropdown related_menu pull-right"><a title="%s" class="relate_menu dropdown-toggle" data-toggle="dropdown"><i class="icon fa fa-list"></i></a>%s</div>' % (_('Related Objects'), ul_html) 
Example 45
Project: django-xadmin   Author: MarkHoo   File: dashboard.py    MIT License 5 votes vote down vote up
def model_admin_url(self, name, *args, **kwargs):
        return reverse(
            "%s:%s_%s_%s" % (self.admin_site.app_name, self.app_label,
            self.model_name, name), args=args, kwargs=kwargs) 
Example 46
Project: django-xadmin   Author: MarkHoo   File: base.py    MIT License 5 votes vote down vote up
def get_admin_url(self, name, *args, **kwargs):
        return reverse('%s:%s' % (self.admin_site.app_name, name), args=args, kwargs=kwargs) 
Example 47
Project: django-xadmin   Author: MarkHoo   File: base.py    MIT License 5 votes vote down vote up
def get_model_url(self, model, name, *args, **kwargs):
        return reverse(
            '%s:%s_%s_%s' % (self.admin_site.app_name, model._meta.app_label,
                             model._meta.model_name, name),
            args=args, kwargs=kwargs, current_app=self.admin_site.name) 
Example 48
Project: django-xadmin   Author: MarkHoo   File: models.py    MIT License 5 votes vote down vote up
def url(self):
        base_url = reverse(self.url_name)
        if self.query:
            base_url = base_url + '?' + self.query
        return base_url 
Example 49
Project: django-outlook-api   Author: spectrumone   File: views.py    MIT License 5 votes vote down vote up
def home(request):
    redirect_uri = request.build_absolute_uri(reverse('tutorial:gettoken'))
    sign_in_url = get_signin_url(redirect_uri)

    return HttpResponse('<a href="' + sign_in_url +'">Click here to sign in and view your mail</a>') 
Example 50
Project: django-outlook-api   Author: spectrumone   File: views.py    MIT License 5 votes vote down vote up
def gettoken(request):
    auth_code = request.GET['code']
    redirect_uri = request.build_absolute_uri(reverse('tutorial:gettoken'))
    token = get_token_from_code(auth_code, redirect_uri)
    access_token = token['access_token']

    # Save the token in the session
    request.session['access_token'] = access_token
    return HttpResponseRedirect(reverse('tutorial:mail')) 
Example 51
Project: django-outlook-api   Author: spectrumone   File: views.py    MIT License 5 votes vote down vote up
def mail(request):
    access_token = request.session['access_token']
    # If there is no token in the session, redirect to home
    if not access_token:
        return HttpResponseRedirect(reverse('tutorial:home'))
    else:
        messages = get_my_messages(access_token)
        return HttpResponse('Messages: {0}'.format(messages)) 
Example 52
Project: django-outlook-api   Author: spectrumone   File: views.py    MIT License 5 votes vote down vote up
def post_events(request):
    access_token = request.session['access_token']
    if not access_token:
        return HttpResponseRedirect(reverse('tutorial:home'))
    else:
        post_event_results = post_my_events(access_token)
        return HttpResponse('Messages: {0}'.format(post_event_results)) 
Example 53
Project: django-outlook-api   Author: spectrumone   File: views.py    MIT License 5 votes vote down vote up
def events(request):
    access_token = request.session['access_token']
    # If there is no token in the session, redirect to home
    if not access_token:
        return HttpResponseRedirect(reverse('tutorial:home'))
    else:
        events = get_my_events(access_token)
        context = { 'events': events['value'] }
        return render(request, 'tutorial/events.html', context) 
Example 54
Project: noke-platform   Author: NokeCodes   File: views.py    MIT License 5 votes vote down vote up
def profile(request, username):
    try:
        profile_user = User.objects.select_related('profile').get(username=username)
    except User.DoesNotExist:
        return HttpResponseRedirect(reverse('users:index'))
    return render(request, 'users/profile.html', {
        'user': profile_user,
    }) 
Example 55
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_registration_view_initial(self):
        """
        A ``GET`` to the ``register`` view uses the appropriate
        template and populates the registration form into the context.

        """
        response = self.client.get(reverse('registration_register'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response,
                                'registration/registration_form.html')
        self.failUnless(isinstance(response.context['form'],
                                   forms.RegistrationForm)) 
Example 56
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_registration_view_success(self):
        """
        A ``POST`` to the ``register`` view with valid data properly
        creates a new user and issues a redirect.

        """
        response = self.client.post(reverse('registration_register'),
                                    data={'username': 'alice',
                                          'email': '[email protected]',
                                          'password1': 'swordfish',
                                          'password2': 'swordfish'})
        self.assertRedirects(response,
                             'http://testserver%s' % reverse('registration_complete'))
        self.assertEqual(RegistrationProfile.objects.count(), 1)
        self.assertEqual(len(mail.outbox), 1) 
Example 57
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_registration_template_name(self):
        """
        Passing ``template_name`` to the ``register`` view will result
        in that template being used.

        """
        response = self.client.get(reverse('registration_test_register_template_name'))
        self.assertTemplateUsed(response,
                                'registration/test_template_name.html') 
Example 58
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_registration_disallowed_url(self):
        """
        Passing ``disallowed_url`` to the ``register`` view will
        result in a redirect to that URL when registration is closed.

        """
        old_allowed = getattr(settings, 'REGISTRATION_OPEN', True)
        settings.REGISTRATION_OPEN = False

        closed_redirect = 'http://testserver%s' % reverse('registration_test_custom_disallowed')

        response = self.client.get(reverse('registration_test_register_disallowed_url'))
        self.assertRedirects(response, closed_redirect)

        settings.REGISTRATION_OPEN = old_allowed 
Example 59
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_registration_success_url(self):
        """
        Passing ``success_url`` to the ``register`` view will result
        in a redirect to that URL when registration is successful.
        
        """
        success_redirect = 'http://testserver%s' % reverse('registration_test_custom_success_url')
        response = self.client.post(reverse('registration_test_register_success_url'),
                                    data={'username': 'alice',
                                          'email': '[email protected]',
                                          'password1': 'swordfish',
                                          'password2': 'swordfish'})
        self.assertRedirects(response, success_redirect) 
Example 60
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_activation_extra_context(self):
        """
        Passing ``extra_context`` to the ``activate`` view will
        correctly populate the context.

        """
        response = self.client.get(reverse('registration_test_activate_extra_context',
                                           kwargs={'activation_key': 'foo'}))
        self.assertEqual(response.context['foo'], 'bar')
        # Callables in extra_context are called to obtain the value.
        self.assertEqual(response.context['callable'], 'called') 
Example 61
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_registration_view_initial(self):
        """
        A ``GET`` to the ``register`` view uses the appropriate
        template and populates the registration form into the context.

        """
        response = self.client.get(reverse('registration_register'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response,
                                'registration/registration_form.html')
        self.failUnless(isinstance(response.context['form'],
                                   forms.RegistrationForm)) 
Example 62
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_registration_view_success(self):
        """
        A ``POST`` to the ``register`` view with valid data properly
        creates a new user and issues a redirect.

        """
        response = self.client.post(reverse('registration_register'),
                                    data={'username': 'alice',
                                          'email': '[email protected]',
                                          'password1': 'swordfish',
                                          'password2': 'swordfish'})
        self.assertRedirects(response,
                             'http://testserver%s' % reverse('registration_complete'))
        self.assertEqual(RegistrationProfile.objects.count(), 1)
        self.assertEqual(len(mail.outbox), 1) 
Example 63
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_registration_extra_context(self):
        """
        Passing ``extra_context`` to the ``register`` view will
        correctly populate the context.

        """
        response = self.client.get(reverse('registration_test_register_extra_context'))
        self.assertEqual(response.context['foo'], 'bar')
        # Callables in extra_context are called to obtain the value.
        self.assertEqual(response.context['callable'], 'called') 
Example 64
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_registration_disallowed_url(self):
        """
        Passing ``disallowed_url`` to the ``register`` view will
        result in a redirect to that URL when registration is closed.

        """
        old_allowed = getattr(settings, 'REGISTRATION_OPEN', True)
        settings.REGISTRATION_OPEN = False

        closed_redirect = 'http://testserver%s' % reverse('registration_test_custom_disallowed')

        response = self.client.get(reverse('registration_test_register_disallowed_url'))
        self.assertRedirects(response, closed_redirect)

        settings.REGISTRATION_OPEN = old_allowed 
Example 65
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_registration_success_url(self):
        """
        Passing ``success_url`` to the ``register`` view will result
        in a redirect to that URL when registration is successful.
        
        """
        success_redirect = 'http://testserver%s' % reverse('registration_test_custom_success_url')
        response = self.client.post(reverse('registration_test_register_success_url'),
                                    data={'username': 'alice',
                                          'email': '[email protected]',
                                          'password1': 'swordfish',
                                          'password2': 'swordfish'})
        self.assertRedirects(response, success_redirect) 
Example 66
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_activation_template_name(self):
        """
        Passing ``template_name`` to the ``activate`` view will result
        in that template being used.

        """
        response = self.client.get(reverse('registration_test_activate_template_name',
                                   kwargs={'activation_key': 'foo'}))
        self.assertTemplateUsed(response, 'registration/test_template_name.html') 
Example 67
Project: django-registration-0.8.0-alpha-1   Author: mick-t   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_activation_extra_context(self):
        """
        Passing ``extra_context`` to the ``activate`` view will
        correctly populate the context.

        """
        response = self.client.get(reverse('registration_test_activate_extra_context',
                                           kwargs={'activation_key': 'foo'}))
        self.assertEqual(response.context['foo'], 'bar')
        # Callables in extra_context are called to obtain the value.
        self.assertEqual(response.context['callable'], 'called') 
Example 68
Project: VisualNN   Author: angelhunt   File: test_views.py    GNU General Public License v3.0 5 votes vote down vote up
def test_caffe_import_by_url(self):
        url = 'https://github.com/Cloud-CV/Fabrik/blob/master/example/caffe/All_CNN.prototxt'
        # Test 1
        response = self.client.post(reverse('caffe-import'),
                                    {'url': url})
        response = json.loads(response.content)
        self.assertEqual(response['result'], 'success')
        # Test 2
        url = 'https://github.com/Cloud-CV/Fabrik/blob/master/some_typo_here'
        response = self.client.post(reverse('caffe-import'),
                                    {'url': url})
        response = json.loads(response.content)
        self.assertEqual(response['result'], 'error')
        self.assertEqual(response['error'], 'Invalid URL\nHTTP Error 404: Not Found') 
Example 69
Project: VisualNN   Author: angelhunt   File: test_views.py    GNU General Public License v3.0 5 votes vote down vote up
def test_caffe_import_by_sample_id(self):
        response = self.client.post(reverse('caffe-import'),
                                    {'sample_id': 'GoogleNet'})
        response = json.loads(response.content)
        self.assertEqual(response['result'], 'success')
        response = self.client.post(reverse('caffe-import'),
                                    {'sample_id': 'vgg15'})
        response = json.loads(response.content)
        self.assertEqual(response['result'], 'error')
        self.assertEqual(response['error'], 'No Prototxt model file found') 
Example 70
Project: VisualNN   Author: angelhunt   File: test_views.py    GNU General Public License v3.0 5 votes vote down vote up
def test_caffe_export(self):
        data = L.Input(shape={'dim': [10, 3, 224, 224]})
        top = L.Convolution(data, kernel_size=3, pad=1, stride=1, num_output=128, dilation=1,
                            weight_filler={'type': 'xavier'}, bias_filler={'type': 'constant'})
        with open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'w') as f:
            f.write(str(to_proto(top)))
        sample_file = open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'r')
        response = self.client.post(reverse('caffe-import'), {'file': sample_file})
        response = json.loads(response.content)
        response['net']['l0']['params']['caffe'] = True
        response['net']['l1']['params']['caffe'] = True
        response = self.client.post(reverse('caffe-export'), {'net': json.dumps(response['net']),
                                                              'net_name': ''})
        response = json.loads(response.content)
        self.assertEqual(response['result'], 'success') 
Example 71
Project: VisualNN   Author: angelhunt   File: test_views.py    GNU General Public License v3.0 5 votes vote down vote up
def test_caffe_import(self):
        # Test 1
        data, label = L.ImageData(source='/dummy/source/', batch_size=32, ntop=2, rand_skip=0,
                                  shuffle=False, new_height=256, new_width=256, is_color=False,
                                  root_folder='/dummy/folder/',
                                  transform_param=dict(crop_size=227, mean_value=[104, 117, 123],
                                                       mirror=True, force_color=False,
                                                       force_gray=False))
        with open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'w') as f:
            f.write(str(to_proto(data, label)))
        sample_file = open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'r')
        response = self.client.post(reverse('caffe-import'), {'file': sample_file})
        response = json.loads(response.content)
        os.remove(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'))
        self.assertGreaterEqual(len(response['net']['l0']['params']), 13)
        self.assertEqual(response['result'], 'success')
        # Test 2
        data, label = L.ImageData(source='/dummy/source/', batch_size=32, ntop=2, rand_skip=0,
                                  shuffle=False, new_height=256, new_width=256, is_color=False,
                                  root_folder='/dummy/folder/', include=dict(phase=caffe.TRAIN),
                                  transform_param=dict(crop_size=227, mean_file='/path/to/file',
                                                       mirror=True, force_color=False,
                                                       force_gray=False))
        with open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'w') as f:
            f.write(str(to_proto(data, label)))
        sample_file = open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'r')
        response = self.client.post(reverse('caffe-import'), {'file': sample_file})
        response = json.loads(response.content)
        os.remove(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'))
        self.assertGreaterEqual(len(response['net']['l0']['params']), 13)
        self.assertEqual(response['result'], 'success') 
Example 72
Project: VisualNN   Author: angelhunt   File: test_views.py    GNU General Public License v3.0 5 votes vote down vote up
def test_caffe_import(self):
        # Test 1
        data, label = L.Data(source='/dummy/source/', backend=P.Data.LMDB, batch_size=32, ntop=2,
                             rand_skip=0, prefetch=10,
                             transform_param=dict(crop_size=227, mean_value=[104, 117, 123],
                                                  mirror=True, force_color=False,
                                                  force_gray=False))
        with open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'w') as f:
            f.write(str(to_proto(data, label)))
        sample_file = open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'r')
        response = self.client.post(reverse('caffe-import'), {'file': sample_file})
        response = json.loads(response.content)
        os.remove(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'))
        self.assertGreaterEqual(len(response['net']['l0']['params']), 10)
        self.assertEqual(response['result'], 'success')
        # Test 2
        data, label = L.Data(source='/dummy/source/', backend=P.Data.LEVELDB, batch_size=32, ntop=2,
                             rand_skip=0, prefetch=10,
                             transform_param=dict(crop_size=227, mean_value=[104, 117, 123],
                                                  mirror=True, force_color=False,
                                                  force_gray=False))
        with open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'w') as f:
            f.write(str(to_proto(data, label)))
        sample_file = open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'r')
        response = self.client.post(reverse('caffe-import'), {'file': sample_file})
        response = json.loads(response.content)
        os.remove(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'))
        self.assertGreaterEqual(len(response['net']['l0']['params']), 10)
        self.assertEqual(response['result'], 'success') 
Example 73
Project: VisualNN   Author: angelhunt   File: test_views.py    GNU General Public License v3.0 5 votes vote down vote up
def test_caffe_import(self):
        data, label = L.HDF5Data(source='/dummy/source/', batch_size=32, ntop=2, shuffle=False)
        with open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'w') as f:
            f.write(str(to_proto(data, label)))
        sample_file = open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'r')
        response = self.client.post(reverse('caffe-import'), {'file': sample_file})
        response = json.loads(response.content)
        os.remove(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'))
        self.assertGreaterEqual(len(response['net']['l0']['params']), 3)
        self.assertEqual(response['result'], 'success') 
Example 74
Project: VisualNN   Author: angelhunt   File: test_views.py    GNU General Public License v3.0 5 votes vote down vote up
def test_caffe_import(self):
        top = L.HDF5Output(file_name='/dummy/filename')
        with open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'w') as f:
            f.write(str(to_proto(top)))
        sample_file = open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'r')
        response = self.client.post(reverse('caffe-import'), {'file': sample_file})
        response = json.loads(response.content)
        os.remove(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'))
        self.assertGreaterEqual(len(response['net']['l0']['params']), 1)
        self.assertEqual(response['result'], 'success') 
Example 75
Project: VisualNN   Author: angelhunt   File: test_views.py    GNU General Public License v3.0 5 votes vote down vote up
def test_caffe_import(self):
        data = L.Input(shape={'dim': [10, 3, 224, 224]})
        with open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'w') as f:
            f.write(str(to_proto(data)))
        sample_file = open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'r')
        response = self.client.post(reverse('caffe-import'), {'file': sample_file})
        response = json.loads(response.content)
        os.remove(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'))
        self.assertGreaterEqual(len(response['net']['l0']['params']), 1)
        self.assertEqual(response['result'], 'success') 
Example 76
Project: VisualNN   Author: angelhunt   File: test_views.py    GNU General Public License v3.0 5 votes vote down vote up
def test_caffe_import(self):
        data, label = L.MemoryData(batch_size=32, ntop=2, channels=3, height=224, width=224)
        with open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'w') as f:
            f.write(str(to_proto(data, label)))
        sample_file = open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'r')
        response = self.client.post(reverse('caffe-import'), {'file': sample_file})
        response = json.loads(response.content)
        os.remove(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'))
        self.assertGreaterEqual(len(response['net']['l0']['params']), 4)
        self.assertEqual(response['result'], 'success') 
Example 77
Project: VisualNN   Author: angelhunt   File: test_views.py    GNU General Public License v3.0 5 votes vote down vote up
def test_caffe_import(self):
        data = L.DummyData(shape={'dim': [10, 3, 224, 224]},
                           data_filler={'type': 'constant'})
        with open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'w') as f:
            f.write(str(to_proto(data)))
        sample_file = open(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'), 'r')
        response = self.client.post(reverse('caffe-import'), {'file': sample_file})
        response = json.loads(response.content)
        os.remove(os.path.join(settings.BASE_DIR, 'media', 'test.prototxt'))
        self.assertGreaterEqual(len(response['net']['l0']['params']), 1)
        self.assertEqual(response['result'], 'success')


# ********** Vision Layers Test ********** 
Example 78
Project: django-xadmin   Author: MarkHoo   File: details.py    MIT License 4 votes vote down vote up
def result_item(self, item, obj, field_name, row):
        if (self.show_all_rel_details or (field_name in self.show_detail_fields)):
            rel_obj = None
            if hasattr(item.field, 'rel') and isinstance(item.field.rel, models.ManyToOneRel):
                rel_obj = getattr(obj, field_name)
            elif field_name in self.show_detail_fields:
                rel_obj = obj

            if rel_obj:
                if rel_obj.__class__ in site._registry:
                    try:
                        model_admin = site._registry[rel_obj.__class__]
                        has_view_perm = model_admin(self.admin_view.request).has_view_permission(rel_obj)
                        has_change_perm = model_admin(self.admin_view.request).has_change_permission(rel_obj)
                    except:
                        has_view_perm = self.admin_view.has_model_perm(rel_obj.__class__, 'view')
                        has_change_perm = self.has_model_perm(rel_obj.__class__, 'change')
                else:
                    has_view_perm = self.admin_view.has_model_perm(rel_obj.__class__, 'view')
                    has_change_perm = self.has_model_perm(rel_obj.__class__, 'change')

            if rel_obj and has_view_perm:
                opts = rel_obj._meta
                try:
                    item_res_uri = reverse(
                        '%s:%s_%s_detail' % (self.admin_site.app_name,
                                             opts.app_label, opts.model_name),
                        args=(getattr(rel_obj, opts.pk.attname),))
                    if item_res_uri:
                        if has_change_perm:
                            edit_url = reverse(
                                '%s:%s_%s_change' % (self.admin_site.app_name, opts.app_label, opts.model_name),
                                args=(getattr(rel_obj, opts.pk.attname),))
                        else:
                            edit_url = ''
                        item.btns.append('<a data-res-uri="%s" data-edit-uri="%s" class="details-handler" rel="tooltip" title="%s"><i class="fa fa-info-circle"></i></a>'
                                         % (item_res_uri, edit_url, _(u'Details of %s') % str(rel_obj)))
                except NoReverseMatch:
                    pass
        return item

    # Media 
Example 79
Project: django-xadmin   Author: MarkHoo   File: importexport.py    MIT License 4 votes vote down vote up
def post(self, request, *args, **kwargs):
        """
        Perform the actual import action (after the user has confirmed he
        wishes to import)
        """
        resource = self.get_import_resource_class()(**self.get_import_resource_kwargs(request, *args, **kwargs))

        confirm_form = ConfirmImportForm(request.POST)
        if confirm_form.is_valid():
            import_formats = self.get_import_formats()
            input_format = import_formats[
                int(confirm_form.cleaned_data['input_format'])
            ]()
            tmp_storage = self.get_tmp_storage_class()(name=confirm_form.cleaned_data['import_file_name'])
            data = tmp_storage.read(input_format.get_read_mode())
            if not input_format.is_binary() and self.from_encoding:
                data = force_text(data, self.from_encoding)
            dataset = input_format.create_dataset(data)

            result = resource.import_data(dataset, dry_run=False,
                                          raise_errors=True,
                                          file_name=confirm_form.cleaned_data['original_file_name'],
                                          user=request.user)

            if not self.get_skip_admin_log():
                # Add imported objects to LogEntry
                logentry_map = {
                    RowResult.IMPORT_TYPE_NEW: ADDITION,
                    RowResult.IMPORT_TYPE_UPDATE: CHANGE,
                    RowResult.IMPORT_TYPE_DELETE: DELETION,
                }
                content_type_id = ContentType.objects.get_for_model(self.model).pk
                for row in result:
                    if row.import_type != row.IMPORT_TYPE_ERROR and row.import_type != row.IMPORT_TYPE_SKIP:
                        LogEntry.objects.log_action(
                            user_id=request.user.pk,
                            content_type_id=content_type_id,
                            object_id=row.object_id,
                            object_repr=row.object_repr,
                            action_flag=logentry_map[row.import_type],
                            change_message="%s through import_export" % row.import_type,
                        )
            success_message = str(_(u'Import finished')) + ' , ' + str(_(u'Add')) + ' : %d' % result.totals[
                RowResult.IMPORT_TYPE_NEW] + ' , ' + str(_(u'Update')) + ' : %d' % result.totals[
                RowResult.IMPORT_TYPE_UPDATE]

            messages.success(request, success_message)
            tmp_storage.remove()

            post_import.send(sender=None, model=self.model)
            model_info = (self.opts.app_label, self.opts.model_name)
            url = reverse('xadmin:%s_%s_changelist' % model_info,
                          current_app=self.admin_site.name)
            return HttpResponseRedirect(url) 
Example 80
Project: django-xadmin   Author: MarkHoo   File: details.py    MIT License 4 votes vote down vote up
def result_item(self, item, obj, field_name, row):
        if (self.show_all_rel_details or (field_name in self.show_detail_fields)):
            rel_obj = None
            if hasattr(item.field, 'rel') and isinstance(item.field.rel, models.ManyToOneRel):
                rel_obj = getattr(obj, field_name)
            elif field_name in self.show_detail_fields:
                rel_obj = obj

            if rel_obj:
                if rel_obj.__class__ in site._registry:
                    try:
                        model_admin = site._registry[rel_obj.__class__]
                        has_view_perm = model_admin(self.admin_view.request).has_view_permission(rel_obj)
                        has_change_perm = model_admin(self.admin_view.request).has_change_permission(rel_obj)
                    except:
                        has_view_perm = self.admin_view.has_model_perm(rel_obj.__class__, 'view')
                        has_change_perm = self.has_model_perm(rel_obj.__class__, 'change')
                else:
                    has_view_perm = self.admin_view.has_model_perm(rel_obj.__class__, 'view')
                    has_change_perm = self.has_model_perm(rel_obj.__class__, 'change')

            if rel_obj and has_view_perm:
                opts = rel_obj._meta
                try:
                    item_res_uri = reverse(
                        '%s:%s_%s_detail' % (self.admin_site.app_name,
                                             opts.app_label, opts.model_name),
                        args=(getattr(rel_obj, opts.pk.attname),))
                    if item_res_uri:
                        if has_change_perm:
                            edit_url = reverse(
                                '%s:%s_%s_change' % (self.admin_site.app_name, opts.app_label, opts.model_name),
                                args=(getattr(rel_obj, opts.pk.attname),))
                        else:
                            edit_url = ''
                        item.btns.append('<a data-res-uri="%s" data-edit-uri="%s" class="details-handler" rel="tooltip" title="%s"><i class="fa fa-info-circle"></i></a>'
                                         % (item_res_uri, edit_url, _(u'Details of %s') % str(rel_obj)))
                except NoReverseMatch:
                    pass
        return item

    # Media