python - 在 Django 中登录后将用户重定向到自定义链接

标签 python django django-login

在过去的几天里,我遇到了很多类似的问题和解决方案,但在我的案例中找不到可行的解决方案。

我的代码是:

urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/$', login  ,{'template_name': 'login_template.html'}),
    url(r'^dashboard/(?P<slug>\w+)/$', login_required(DashboardHomeViewClass.as_view()),name = "dashboard"),
]

views.py

class DashboardHomeViewClass(View):
    def get(self, request, *args, **kwargs):


        device_user_objects = device_user_data.objects.filter(User_Name = request.user.username)
        device_parameter_objects = device_parameter_data.objects.all()

        device_alias_list = []
        device_id_list = []

        queryset = []

        light_list = []


        for device in device_user_objects:
            device_alias_list.append(device.Device_Alias_Data)
            device_id_list.append(device.Device_Id_Data)

        default_device = device_id_list[0]



        slug = self.kwargs.get("slug")

        for device_id in device_id_list:

            if slug == device_id:
                queryset = device_parameter_objects.filter(Device_Id = slug)


        for data_object in queryset:

            light_list.append(data_object.Light)


        recent_light = light_list[-1]   

        context_logged = {'device_user_objects': device_user_objects,
        'light_list': light_list,
        'recent_light': recent_light}


        return render(request, "dashboardhometemplate.html", context_logged)

dashboardhometemplate.html 中使用此上下文的 HTML 部分

{%for item in device_user_objects%}
    <li> <a  href="/dashboard/{{item.Device_Id_Data}}" aria-expanded="false"><i class="fa fa-bar-chart"></i><span class="hide-menu">{{item.Device_Alias_Data}}</span></a>
{% endfor %}

现在我想做的是

登录后将用户重定向到页面http://127.0.0.1:8000/dashboard/ {{在views.py中声明和定义的default_device变量的值}}

最佳答案

你可以这样做

from django.shortcuts import redirect, render


def login_view_function(request):
    # ....your code to determine if login allowed or not and populate the 'login_success' variable.

    if login_success:
        return redirect('/your/url_here')
    else:
        return render(request, 'login.html', {})

关于python - 在 Django 中登录后将用户重定向到自定义链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51220760/

相关文章:

python - 如果我有外键,我该如何在 Django 中执行此 "order by"?

django - 有什么方法可以更改用户身份验证登录页面中的用户名字段标签?

python - 为什么我收到 RuntimeError : generator raised StopIteration? 以及如何解决它?

python - 在 OSX 上安装多个版本的 python 包

python - Json,抓取到网页 - python

django - Django中如何阻止登录成功后访问登录页面?

python - 如何从多个上下文对象中选择 get_context_data 进行分页?

python - 奇怪的 django 导入行为

python - 上传前在本地进行一些处理