简体   繁体   English

登录Django后根据用户名将用户重定向到自定义url

[英]Redirect user to custom url based on the username after Login Django

Hello?你好? I am trying to redirect a particular user to a custom page once they log in in django.我试图在特定用户登录 Django 后将其重定向到自定义页面。 The Admin will be directed to their usual admin interface while this particular user will go to their own custom page.管理员将被定向到他们通常的管理界面,而该特定用户将转到他们自己的自定义页面。 I have written this code and placed it in my views我已经编写了这段代码并将其放在我的视图中

def custLogin(request):
    if request.user.username == '***':
        return HttpResponseRedirect('http://********************.html')
    else:
        return login(request,template_name='login.html')

I have pointed the accounts/login url in urls.py to custLogin as below我已将 urls.py 中的帐户/登录 url 指向 custLogin,如下所示

(r'^accounts/login/', custLogin),

I however keep getting the error但是我不断收到错误

Caught NoReverseMatch while rendering: Reverse for 'django.contrib.auth.views.login' with arguments '()' and keyword arguments '{}' not found.

Any pointers please?请问有什么指点吗?

Maybe, you should use redirect shortcut, which returns an HttpResponseRedirect , to point your users to different places after custLogin view processed.也许,您应该使用重定向快捷方式,它返回一个HttpResponseRedirect ,在custLogin视图处理后将您的用户指向不同的位置。

from django.shortcuts import redirect
def custLogin(request):
    if request.user.is_staff:
        return redirect('/some/admin/url')
    else:
        return redirect('/some/regular/user/url')

As documentation says, you can use the redirect() function in a number of ways: by passing a view name, an object or url.正如文档所说,您可以通过多种方式使用redirect()函数:通过传递视图名称、对象或 url。 See documentation for more info有关更多信息,请参阅文档

Note, that I use is_staff user field to determine: is user an admin or not.请注意,我使用is_staff用户字段来确定:用户是否为管理员。

In your template, you may have forgotten to do this at the beginning of your template:在您的模板中,您可能忘记在模板开头执行此操作:

{% load from future url %}

This is useful when using:这在使用时很有用:

{% url 'name_of_my_url_inurl.py' %}

For redirecting each user to his own page use reverse要将每个用户重定向到他自己的页面,请使用reverse

First create url route which accepts parameter.首先创建接受参数的 url 路由。 It's described here在这里描述

And redirect like并像重定向一样

return HttpResponseRedirect(reverse('arch-summary', args=[1945]))

where arch-summary - named url, and in list args - parameters for it.其中arch-summary - 命名的 url,在列表中args - 它的参数。 Examplehere示例在这里

To distinguish admin user from usual user, check it in view and redirect to different url.要区分管理员用户和普通用户,请在视图中检查并重定向到不同的 url。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM