将某个用户重定向到django中的某个视图

时间:2014-12-29 01:08:29

标签: python django

我需要知道如何在登录后将Django视图中的用户重定向到某个页面。 我们说我们有3种类型的用户和3种类型的页面,我希望每种类型都指向某个页面,同时也没有权限查看其他页面。< / p>

2 个答案:

答案 0 :(得分:2)

您可以这样做:

from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
@login_required
def home(request):
    return HttpResponseRedirect(
               reverse(custom_view, 
                       args=[request.user.username]))

此处,custom_view应该是您的用户特定视图。这假设你有:

LOGIN_REDIRECT_URL = '/profiles/home'

您已配置了urlpattern:

(r'^profiles/home', 'myapp.views.home')

您可以添加帐户类型检查并重定向到正确的视图。

答案 1 :(得分:0)

我最近通过对django.contrib.auth提供的LoginView进行子类化编写了一些类似的功能。好的,从根目录创建第一页,将其命名为login: python manage.py startapp login。使此文件存在<projectRoot>/login/templates/registration/login.html在所述文件中添加此代码,它或多或少地从bootstrap的登录表单中剪切和粘贴,但使用一些标准的django模板语言绑定到预期的AuthenticationForm字段。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">
    <title>Signin to yourWebsite.com</title>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
  </head>
  <body class="text-center">
    <form class="form-signin" method="post" action="{% url 'login' %}?next=clockin">
    {% csrf_token %}
      <img class="mb-4" src="https://getbootstrap.com/assets/brand/bootstrap-solid.svg" alt="" width="72" height="72">
      <h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
      <label for="inputEmail" class="sr-only">Email address</label>
      <!--input id="inputEmail" class="form-control" placeholder="Email address" required="True" autofocus="" type="email"-->
      {{form.username}}
      <label for="id_password" class="sr-only">Password</label>
      {{form.password}}
      <!--input id="inputPassword" class="form-control" placeholder="Password" required="True" type="password"-->
      <div class="checkbox mb-3">
        <label>
          <input value="remember-me" type="checkbox"> Remember me
        </label>
      </div>
      <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
      <p class="mt-5 mb-3 text-muted">© 2018</p>
    </form>
  </body>
</html>
<script>
    $("#id_password").attr({
        "class":"form-control",
        "placeholder":"Password",
        "required":"True",
        "type":"password",
    });
    $("#id_username").attr({"class":"form-control",
        "placeholder":"Email address",
        "required":"True",
        "type":"email",
    });
</script>
<style>
html,
body {
  height: 100%;
}

body {
  display: -ms-flexbox;
  display: -webkit-box;
  display: flex;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -webkit-box-align: center;
  align-items: center;
  -webkit-box-pack: center;
  justify-content: center;
  padding-top: 40px;
  padding-bottom: 40px;
  background-color: #f5f5f5;
}

.form-signin {
  width: 100%;
  max-width: 330px;
  padding: 15px;
  margin: 0 auto;
}
.form-signin .checkbox {
  font-weight: 400;
}
.form-signin .form-control {
  position: relative;
  box-sizing: border-box;
  height: auto;
  padding: 10px;
  font-size: 16px;
}
.form-signin .form-control:focus {
  z-index: 2;
}
.form-signin input[type="email"] {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}
.form-signin input[type="password"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}
</style>

接下来,继承内置视图并覆盖重定向部分。在login.views.py中,添加:

from django.contrib.auth.views import LoginView

class CustomLoginview(LoginView):

    def get_redirect_url(self):
        if self.request.user.groups.filter(name="customer").exists():
            return 'invoice'
        return super().get_redirect_url()

最后,更新urls.py:

from login.views import CustomLoginview

urlpatterns = [
    path('', CustomLoginview.as_view(), name='login'),

如果用户是客户,我告诉登录页面转到我的下一个应用程序'发票',否则它将转到我在设置文件中指定的默认值。显然你可以解释3种类型用户的概念,这与基于用户名称的路由不同,不确定如何得到2个upvotes。