无法以编程方式打开django员工旗帜

时间:2015-06-06 13:39:30

标签: python django

我从数据库中获取用户,然后is_staff=True然后保存它。但是它失败了。

为什么我不能以实际工作人员的身份使用此代码保存用户?

def approve_staff(self,request,username,):
    if request.user.is_superuser:
        u=User.objects.filter(username=username)
        if u.exists():
            u[0].is_staff=True;
            u[0].save() #
            print u[0],u[0].is_staff
    from django.http import HttpResponseRedirect
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

2 个答案:

答案 0 :(得分:1)

并不一定能解决您的问题,但Django获取单个记录的方法是Queryset.get

    try:
        u=User.objects.get(username=username)
    except User.DoesNotExist:
        raise Http404() 
    u.is_staff=True;
    u.save() #
    print u, u.is_staff

此外,您的视图应该只接受POST请求。

答案 1 :(得分:0)

你不能做一个

if(Auth::attempt(['email' => $request->email, 'password' => $request->password]))
{
   //using role with an expectation that you have one relation method named role defined in User model
   //and roles table stores user type as name

   if(Auth::user()->role->name == 'admin')
   {
      return redirect()->to('/administrator/dashboard');
   }
   elseif(Auth::user()->role->name == 'jobseeker')
   {
      return redirect()->to('jobseeker/dashboard');
   }
}

它将为过滤器找到的每个对象更新数据(无需调用save())。