Python django.shortcuts.reverse() Examples

The following are 30 code examples of django.shortcuts.reverse(). 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.shortcuts , or try the search function .
Example #1
Source File: views.py    From BookForum with MIT License 6 votes vote down vote up
def avatar_edit(request):
    if request.method == 'POST':
        form = AvatarForm(request.POST, request.FILES)
        if form.is_valid():
            request.user.avatar = form.cleaned_data['avatar']
            request.user.save()

            messages.success(request, '成功修改头像')

            redirect_url = reverse('User:avatar_edit')
            return redirect(redirect_url)

    else:
        form = AvatarForm()
        form.data['avatar'] = request.user.avatar

    return render(request, 'Auth/avatar_edit.html', context={
        'form': form,
    }) 
Example #2
Source File: test_api.py    From ontask_b with MIT License 6 votes vote down vote up
def test_table_json_create_error(self):
        # Create a second workflow
        response = self.client.post(
            reverse('workflow:api_workflows'),
            {'name': tests.wflow_name + '2', 'attributes': {'one': 'two'}},
            format='json')

        # Get the only workflow in the fixture
        workflow = models.Workflow.objects.get(id=response.data['id'])

        # Upload the table
        response = self.client.post(
            reverse('table:api_ops', kwargs={'wid': workflow.id}),
            {'data_frame': self.incorrect_table_1},
            format='json')

        self.assertTrue(
            'The data has no column with unique values per row' in
            response.data
        ) 
Example #3
Source File: test_api.py    From ontask_b with MIT License 6 votes vote down vote up
def test_table_try_pandas_overwrite(self):
        # Upload a table and try to overwrite an existing one (should fail)

        # Get the only workflow in the fixture
        workflow = models.Workflow.objects.all()[0]

        # Override the table
        response = self.client.post(
            reverse(
                'table:api_pops',
                kwargs={'wid': workflow.id}),
            self.new_table,
            format='json')

        # Check that the right message is returned
        self.assertIn(
            'Post request requires workflow without a table',
            response.data['detail']) 
Example #4
Source File: views.py    From Django-blog with MIT License 6 votes vote down vote up
def get(self, request, code):
        code_obj = EmailVerifyCode.objects.filter(code=code, type='register').last()  # last取默认排序后的最后一个
        # timestamp = (now() - code_obj.add_time).total_seconds()

        # 验证码过期以后再做吧, 不然又得要写多一个重发验证码
        if code_obj:  # and timestamp < 600:
            user = get_object_or_404(User, email=code_obj.email, is_active=False)
            user.is_active = True
            code_obj.is_used = True
            user.save()
            code_obj.save()

            login(request, user)
            messages.success(request, '激活成功, 欢迎加入本博客系统')
            return redirect(reverse('blog:index'))

        messages.success(request, '验证码有误')
        return redirect(reverse('user:login')) 
Example #5
Source File: dataproduct_extras.py    From tom_base with GNU General Public License v3.0 6 votes vote down vote up
def upload_dataproduct(context, obj):
    user = context['user']
    initial = {}
    if isinstance(obj, Target):
        initial['target'] = obj
        initial['referrer'] = reverse('tom_targets:detail', args=(obj.id,))
    elif isinstance(obj, ObservationRecord):
        initial['observation_record'] = obj
        initial['referrer'] = reverse('tom_observations:detail', args=(obj.id,))
    form = DataProductUploadForm(initial=initial)
    if not settings.TARGET_PERMISSIONS_ONLY:
        if user.is_superuser:
            form.fields['groups'].queryset = Group.objects.all()
        else:
            form.fields['groups'].queryset = user.groups.all()
    return {'data_product_form': form} 
Example #6
Source File: test_api.py    From ontask_b with MIT License 6 votes vote down vote up
def test_table_pandas_update(self):
        # Get the only workflow in the fixture
        workflow = models.Workflow.objects.all()[0]

        # Transform new table into string
        r_df = pd.DataFrame(self.new_table)
        r_df = pandas.detect_datetime_columns(r_df)

        # Upload a new table
        self.client.put(
            reverse(
                'table:api_pops',
                kwargs={'wid': workflow.id}),
            {'data_frame': serializers.df_to_string(r_df)},
            format='json')

        # Refresh wflow (has been updated)
        workflow = models.Workflow.objects.get(id=workflow.id)

        # Load the df from the db
        dframe = pandas.load_table(workflow.get_data_frame_table_name())

        # Compare both elements
        self.compare_tables(r_df, dframe) 
Example #7
Source File: search.py    From GetTogether with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def delete_event_searchable(event):
    site = Site.objects.get(id=1)
    if settings.DEBUG:
        schema = "http"
    else:
        schema = "https"
    event_url = "%s://%s%s" % (schema, site.domain, event.get_absolute_url())
    origin_url = "%s://%s%s" % (schema, site.domain, reverse("searchables"))

    md5 = hashlib.md5()
    federation_url = event_url.split("/")
    federation_node = "/".join(federation_url[:3])
    federation_id = "/".join(federation_url[:5])
    md5.update(bytes(federation_id, "utf8"))
    event_uri = federation_node + "/" + md5.hexdigest()

    try:
        searchable = Searchable.objects.get(event_uri=event_uri)
        searchable.delete()
    except:
        pass 
Example #8
Source File: views.py    From yata with GNU General Public License v3.0 6 votes vote down vote up
def delete(request):
    try:
        if request.session.get('player'):
            print('[view.yata.delete] delete account')
            tId = request.session["player"].get("tId")
            player = Player.objects.filter(tId=tId).first()
            factionId = player.factionId
            faction = Faction.objects.filter(tId=factionId).first()
            try:
                faction.delKey(tId)
                faction.save()
            except BaseException:
                pass
            player.delete()
            del request.session['player']

        print('[view.yata.delete] redirect to logout')
        return HttpResponseRedirect(reverse('logout'))

    except Exception as e:
        return returnError(exc=e, session=request.session) 
Example #9
Source File: views.py    From peering-manager with Apache License 2.0 6 votes vote down vote up
def get(self, request):
        if not request.user.is_staff and not request.user.is_superuser:
            messages.error(request, "You do not have the rights to index peer records.")
            return redirect(reverse("home"))

        last_synchronization = PeeringDB().get_last_synchronization()
        sync_time = last_synchronization.time if last_synchronization else 0

        context = {
            "last_sync_time": sync_time,
            "peeringdb_contact_count": Contact.objects.count(),
            "peeringdb_network_count": Network.objects.count(),
            "peeringdb_networkixlan_count": NetworkIXLAN.objects.count(),
            "peer_record_count": PeerRecord.objects.count(),
        }
        return render(request, "peeringdb/cache.html", context) 
Example #10
Source File: test_api.py    From ontask_b with MIT License 6 votes vote down vote up
def test_table_pandas_JSON_get(self):
        # Get the only workflow in the fixture
        workflow = models.Workflow.objects.all()[0]

        # Get the data through the API
        response = self.client.get(
            reverse('table:api_merge', kwargs={'wid': workflow.id}))

        workflow = models.Workflow.objects.all()[0]

        # Transform new table into string
        r_df = pd.DataFrame(response.data['src_df'])
        r_df = pandas.detect_datetime_columns(r_df)

        # Load the df from the db
        dframe = pandas.load_table(workflow.get_data_frame_table_name())

        # Compare both elements and check wf df consistency
        self.compare_tables(r_df, dframe) 
Example #11
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 6 votes vote down vote up
def scan_scan_list(request: HttpRequest, scan_list_id: int) -> HttpResponse:
    """Schedule the scan of a scan list."""
    scan_list = get_object_or_404(
        ScanList.objects.prefetch_related(Prefetch(
            'sites',
            queryset=Site.objects.select_related('last_scan') \
                .annotate_most_recent_scan_start() \
                .annotate_most_recent_scan_end_or_null())
        ), pk=scan_list_id)
    was_any_site_scannable = scan_list.scan()
    if was_any_site_scannable:
        num_scanning_sites = Scan.objects.filter(end__isnull=True).count()
        messages.success(request,
            _("Scans for this list have been scheduled. "+ \
              "The total number of sites in the scanning queue "+ \
              "is %i (including yours)." % num_scanning_sites))
    else:
        messages.warning(request,
            _('All sites have been scanned recently. Please wait 30 minutes and try again.'))

    return redirect(reverse('frontend:view_scan_list', args=(scan_list_id,))) 
Example #12
Source File: test_api.py    From ontask_b with MIT License 6 votes vote down vote up
def test_table_JSON_merge_to_empty(self):
        # Get the only workflow in the fixture
        workflow = models.Workflow.objects.all()[0]

        # Get the data through the API
        response = self.client.put(
            reverse('table:api_merge', kwargs={'wid': workflow.id}),
            {
                "src_df": self.new_table,
                "how": "inner",
                "left_on": "sid",
                "right_on": "sid"
            },
            format='json')

        self.assertEqual(
            response.data['detail'],
            'Unable to perform merge operation: '
            + 'Merge operation produced a result with no rows') 
Example #13
Source File: test_api.py    From ontask_b with MIT License 6 votes vote down vote up
def test_table_pandas_merge_to_empty(self):
        # Get the only workflow in the fixture
        workflow = models.Workflow.objects.all()[0]

        # Transform new table into string
        r_df = pd.DataFrame(self.new_table)

        # Get the data through the API
        response = self.client.put(
            reverse('table:api_pmerge', kwargs={'wid': workflow.id}),
            {
                "src_df": serializers.df_to_string(r_df),
                "how": "inner",
                "left_on": "sid",
                "right_on": "sid"
            },
            format='json')

        self.assertEqual(response.data['detail'],
            'Unable to perform merge operation: '
            + 'Merge operation produced a result with no rows')

    # Merge with inner values 
Example #14
Source File: test_api.py    From ontask_b with MIT License 6 votes vote down vote up
def test_table_JSON_update(self):
        # Get the only workflow in the fixture
        workflow = models.Workflow.objects.all()[0]

        # Transform new table into string
        r_df = pd.DataFrame(self.new_table)
        r_df = pandas.detect_datetime_columns(r_df)

        # Upload a new table
        self.client.put(
            reverse(
                'table:api_ops',
                kwargs={'wid': workflow.id}),
            {'data_frame': self.new_table},
            format='json')

        # Refresh wflow (has been updated)
        workflow = models.Workflow.objects.get(id=workflow.id)

        # Load the df from the db
        dframe = pandas.load_table(workflow.get_data_frame_table_name())

        # Compare both elements
        self.compare_tables(r_df, dframe) 
Example #15
Source File: test_api.py    From ontask_b with MIT License 6 votes vote down vote up
def test_table_try_JSON_overwrite(self):
        # Upload a table and try to overwrite an existing one (should fail)

        # Get the only workflow in the fixture
        workflow = models.Workflow.objects.all()[0]

        # Override the table
        response = self.client.post(
            reverse(
                'table:api_ops',
                kwargs={'wid': workflow.id}),
            self.new_table,
            format='json')

        # Check that the right message is returned
        self.assertIn(
            'Post request requires workflow without a table',
            response.data['detail']) 
Example #16
Source File: table_display.py    From ontask_b with MIT License 6 votes vote down vote up
def display_view(
    request: http.HttpRequest,
    pk: Optional[int] = None,
    workflow: Optional[models.Workflow] = None,
    view: Optional[models.View] = None,
) -> http.HttpResponse:
    """Render the skeleton of the table view.

    :param request: HTTP request
    :param pk: PK of the view to use
    :param workflow: Workflow current being used
    :param view: View being displayed (set by the decorators)
    :return: Initial rendering of the page with the table skeleton
    """
    del pk
    return services.render_table_display_page(
        request,
        workflow,
        view,
        view.columns.all(),
        reverse('table:display_view_ss', kwargs={'pk': view.id}),
    ) 
Example #17
Source File: table_display.py    From ontask_b with MIT License 6 votes vote down vote up
def display(
    request: http.HttpRequest,
    workflow: Optional[models.Workflow] = None,
) -> http.HttpResponse:
    """Render the page base for displaying the table.

    :param request: HTTP request
    :param workflow: Workflow being manipulated (set by the decorators)
    :return: Initial rendering of the page with the table skeleton
    """
    if workflow.nrows == 0:
        # Table is empty, redirect to data upload
        return redirect('dataops:uploadmerge')

    return services.render_table_display_page(
        request,
        workflow,
        None,
        workflow.columns.all(),
        reverse('table:display_ss'),
    ) 
Example #18
Source File: views.py    From ontask_b with MIT License 6 votes vote down vote up
def page_view(
    request: http.HttpRequest,
    pk: int,
    workflow: Optional[models.Workflow] = None,
) -> http.HttpResponse:
    """View the content of one of the logs.

    :param request: Http Request received
    :param pk: Primary key of the log to view
    :param workflow: Workflow being manipulated (set by the decorators)
    :return: Http response rendering the view.html
    """
    # Get the log item
    log_item = workflow.logs.filter(pk=pk, user=request.user).first()

    # If the log item is not there, flag!
    if not log_item:
        messages.error(request, _('Incorrect log number requested'))
        return redirect(reverse('logs:index'))

    return render(
        request,
        'logs/view.html',
        {'log_item': log_item, 'c_vals': log_item.payload}) 
Example #19
Source File: views.py    From BookForum with MIT License 6 votes vote down vote up
def add_tag(request):
    if request.method == 'POST':
        form = AddTagForm(request.POST)
        if form.is_valid():
            form.save()

            messages.success(request, '你成功添加了一个tag,现在可以用其添加书籍')
            redirect_url = reverse('Content:add_node')
            return redirect(redirect_url)
    else:
        form = AddTagForm()

    context = {
        'form': form,
    }
    return render(request, 'Content/add_tag.html', context=context) 
Example #20
Source File: __init__.py    From ontask_b with MIT License 6 votes vote down vote up
def login(self, uemail):
        self.open(reverse('accounts:login'))
        WebDriverWait(self.selenium, 10).until(
            EC.presence_of_element_located((By.ID, 'id_username')))
        WebDriverWait(self.selenium, 10).until_not(
            EC.visibility_of_element_located((By.ID, 'div-spinner'))
        )
        self.selenium.find_element_by_id('id_username').send_keys(uemail)
        self.selenium.find_element_by_id('id_password').send_keys(boguspwd)
        self.selenium.find_element_by_id('submit-id-sign_in').click()
        # Wait for the user profile page
        WebDriverWait(self.selenium, 10).until(
            EC.visibility_of_element_located(
                (By.XPATH, '//div[@id="workflow-index"]')
            )
        )

        self.assertIn('reate a workflow', self.selenium.page_source) 
Example #21
Source File: views.py    From BookForum with MIT License 6 votes vote down vote up
def add_publishing(request):
    if request.method == 'POST':
        form = AddPublishingForm(request.POST)
        if form.is_valid():
            form.save()

            messages.success(request, '你成功添加了一个出版社,现在可以为其增添书籍')
            redirect_url = reverse('Content:add_node')
            return redirect(redirect_url)
    else:
        form = AddPublishingForm()

    context = {
        'form': form
    }
    return render(request, 'Content/add_publishing.html', context=context) 
Example #22
Source File: test_office_access.py    From byro with Apache License 2.0 6 votes vote down vote up
def test_member_add(full_testdata, logged_in_client, user):
    response = logged_in_client.get(reverse("office:members.add"), follow=True)
    assert response.status_code == 200

    response = logged_in_client.post(
        reverse("office:members.add"),
        {
            "member__number": "23",
            "member__name": "Torsten Est",
            "membership__start": str(now().date()),
            "membership__interval": "1",
            "membership__amount": "10",
        },
        follow=True,
    )
    assert response.status_code == 200
    assert b'"alert alert-success"' in response.content
    assert response.resolver_match.url_name == "members.data" 
Example #23
Source File: test_office_access.py    From byro with Apache License 2.0 6 votes vote down vote up
def test_transaction_detail(full_testdata, logged_in_client, user):
    # Balanced transaction
    response = logged_in_client.get(
        reverse("office:finance.transactions.detail", kwargs={"pk": 1}), follow=True
    )
    assert response.status_code == 200

    # Unbalanced transaction, credit
    response = logged_in_client.get(
        reverse("office:finance.transactions.detail", kwargs={"pk": 167}), follow=True
    )
    assert response.status_code == 200

    # Unbalanced transaction, debit
    response = logged_in_client.get(
        reverse("office:finance.transactions.detail", kwargs={"pk": 163}), follow=True
    )
    assert response.status_code == 200 
Example #24
Source File: views.py    From BookForum with MIT License 6 votes vote down vote up
def add_node(request):
    if request.method == 'POST':
        form = AddNodeForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()

            messages.success(request, "成功增加节点")
            slug = form.instance.slug
            redirect_url = reverse('Content:book', kwargs={'slug': slug})
            return redirect(redirect_url)
    else:
        form = AddNodeForm()

    context = {
        'form': form,
    }
    return render(request, 'Content/add_node.html', context=context) 
Example #25
Source File: views.py    From BookForum with MIT License 6 votes vote down vote up
def password_change(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.POST)
        form.user = request.user
        if form.is_valid():
            password = form.cleaned_data['new_password1']
            request.user.set_password(password)
            request.user.save()
            logout(request)

            messages.success(request, '成功修改密码,请重新登陆')

            redirect_url = reverse('User:login')
            return redirect(redirect_url)
    else:
        form = PasswordChangeForm()

    return render(request, 'Auth/password_change.html', context={
        'form': form,
    }) 
Example #26
Source File: test_api.py    From ontask_b with MIT License 6 votes vote down vote up
def test_workflow_create(self):
        # Trying to create an existing wflow and detecting its duplication
        response = self.client.post(
            reverse('workflow:api_workflows'),
            {'name': tests.wflow_name})

        # Message should flag the existence of the wflow
        self.assertIn('Workflow could not be created.',
            response.data.get('detail', ''))

        # Create a second one
        response = self.client.post(
            reverse('workflow:api_workflows'),
            {'name': tests.wflow_name + '2', 'attributes': {'one': 'two'}},
            format='json')

        # Compare the workflows
        workflow = models.Workflow.objects.get(name=tests.wflow_name + '2')
        self.compare_wflows(response.data, workflow) 
Example #27
Source File: views.py    From BookForum with MIT License 6 votes vote down vote up
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            user = User.objects.create_user(
                username=data['username'],
                password=data['password'],
                email=data['email'],
            )
            user.first_name = data.get('first_name')
            user.last_name = data.get('last_name')
            user.is_confirmed = False

            user.save()
            messages.success(request, '你成功注册了一个用户')

            redirect_url = reverse('Content:index')
            return redirect(redirect_url)
    else:
        form = RegisterForm()

    return render(request, 'Auth/register.html', context={
        'form': form,
    }) 
Example #28
Source File: test_api.py    From ontask_b with MIT License 6 votes vote down vote up
def test_table_pandas_get(self):
        # Get the only workflow in the fixture
        workflow = models.Workflow.objects.all()[0]

        # Get the data through the API
        response = self.client.get(
            reverse('table:api_pops', kwargs={'wid': workflow.id}))

        # Transform the response into a data frame
        r_df = serializers.string_to_df(response.data['data_frame'])

        # Load the df from the db
        dframe = pandas.load_table(workflow.get_data_frame_table_name())

        # Compare both elements
        self.compare_tables(r_df, dframe) 
Example #29
Source File: events.py    From GetTogether with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_absolute_url(self):
        return reverse(
            "show-common-event", kwargs={"event_id": self.id, "event_slug": self.slug}
        ) 
Example #30
Source File: events.py    From GetTogether with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_absolute_url(self):
        return reverse("show-place", kwargs={"place_id": self.id})