如果在django视图中为经过身份验证的用户

时间:2018-03-07 01:35:29

标签: django django-models django-views

晚上好,

我的视图只有以超级用户身份登录才有效,但不是“departmentsupervisor”

def detail_employee(request, pk, employee_pk):
    department = get_object_or_404(Department, pk=pk)
    print(department.supervisor, request.user.username)
    if request.user.username == department.supervisor or request.user.is_superuser:
        employee = get_object_or_404(Employee, department__pk=pk, pk=employee_pk)
        review = get_object_or_404(Result, pk=pk)
        print(employee, review.id)
        return render(request, 'review_employee.html', {'employee': employee})
return redirect('dept_employees', pk=department.pk)

我使用用户记录的打印进行验证是== department.supervisor,但是if语句被跳过,如果我使用超级用户登录则可以正常工作。

我试着看看我在这里做错了什么。

由于

修改添加模型。

    class Department(models.Model):
        name = models.CharField(max_length=75, unique=True)
        description = models.CharField(max_length=100)
        supervisor = models.ForeignKey(User, related_name='supervisor', on_delete=models.CASCADE)

1 个答案:

答案 0 :(得分:0)

按如下方式更改protected override void OnModelCreating(DbModelBuilder builder){ builder.Entity<IdentityUserRole>().HasKey(i => new { i.UserId, i.RoleId }).ToTable("AppUserRoles"); } 条件/ /

if


if request.user == department.supervisor or request.user.is_superuser: request.user.username类型,其中strdepartment.supervisour类对象