如何添加' is_logged_in'条件以及django python中的另一个if语句?

时间:2017-12-28 06:26:52

标签: javascript jquery python django

这是我的views.py for search。

 @csrf_exempt
    def search(request):
        if request.method == 'POST':
            name = request.POST.get('name')
            loc = request.POST.get('location')
            bussinessName = request.POST.get('bussinessName')
            d = {
                'name': name,
                'loc': loc,
                'bussinessName': bussinessName,

            }
            return render(request, "search.html", d);
        else:
        # do the thing you want to do in GET method

            return render(request,"search.html",{});

我需要添加一个会话来获取id。这就是我获取成功页面的ID

的方法
def success(request):
    if('is_logged_in' in request.session):
        id = request.session['authToken'];
        return render(request,"success.html",{'uid':id});
    else:
        return render(request,"success.html",{});

我如何才能在搜索中添加此会话。我是Django的初学者,我对此并不太了解。请帮我为我的搜索进行会议..

2 个答案:

答案 0 :(得分:0)

登录后,您可以将会话设置为

request.session['authToken'] = id

检查用户是否已登录,只检查'authToken'是否是请求会话中的密钥。所以这里是代码

@csrf_exempt
def search(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        loc = request.POST.get('location')
        bussinessName = request.POST.get('bussinessName')
        d = {
            'name': name,
            'loc': loc,
            'bussinessName': bussinessName,
            'is_logged_in': True if 'authToken' in request.session.keys() else False
        }
        return render(request, "search.html", d);
    else:
    # do the thing you want to do in GET method

        return render(request,"search.html",{});

因此,如果没有为该用户设置会话,'is_logged_in'将为False,否则为True

答案 1 :(得分:0)

要检查某人是否已登录,我会依赖于request.user.is_authenticated,依赖于Django身份验证框架。

结帐https://docs.djangoproject.com/en/2.0/topics/auth/default/#limiting-access-to-logged-in-users

要设置request.user变量,我总是使用发布到username的表单(包含password/admin/login/?next={{ request.path }}字段),以返回到完全相同的页面但随后登录。