首页 > 解决方案 > Django how to only allow specific users to see a page

问题描述

my models.py

class Utilizador(AbstractBaseUser):
   id = models.AutoField(db_column='ID', primary_key=True)
   departamentoid = models.ForeignKey(Departamento, models.DO_NOTHING, db_column='DepartamentoID', blank=True, null=True)
   email = models.CharField(db_column='Email', max_length=255, blank=True, null=True, unique=True)
   nome = models.CharField(db_column='Nome', max_length=255, blank=True, null=True)

class Inscrio(models.Model):
   id = models.AutoField(db_column='ID', primary_key=True)
   utilizadorid = models.ForeignKey('Utilizador', models.DO_NOTHING, db_column='UtilizadorID')
   participanteinfoid = models.ForeignKey('Participanteinfo', models.DO_NOTHING, db_column='ParticipanteinfoID')

my view.py

def ver_col(request, pk):
   user = Utilizador.objects.get(id=request.user.id)
   insc = Inscrio.objects.get(utilizadorid=request.user.id)

   if  request.user.is_authenticated:
       if request.user.id==insc.utilizadorid.id:
           return render(request, 'main/ver_col.html', 
                        {
                         "insc": insc
                        })

So, I want users to see this "ver_col.html" but they are only allowed to enter the pages with the UtilizadorID (of the table Inscrio) associated with the user logged in at the moment (request.user.id or request.user).

Basically I want all users to be able to see the template but only their own data

标签: pythondjangodjango-queryset

解决方案


不确定您要实现什么,但如果 pk 是用户模型的 pk 那么,

if request.user.id== pk

意味着当前登录的用户只查看自己的页面和一些其他用户的页面。这应该在您对用户进行身份验证之后进行。


推荐阅读