首页 > 解决方案 > 我想将匹配项分配给我在 django admin 中选择的用户

问题描述

我只需要将报告分配给我从 Django Admin 授权的用户。他们应该无法查看数据库中的所有报告。这是我的代码:

模型.py:

from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class Match(models.Model):

    def __str__(self):
        return self.name

    name = models.CharField(max_length = 100)
    url = models.CharField(max_length = 1000)

视图.py:

from django.shortcuts import render
from .models import Match
from django.http import HttpResponse

# Create your views here.

def index(request):
    all_matches = Match.objects.all()
    return render(request, 'landing.html' , {"all_matches" : all_matches})

def upload(request):
    return render(request, 'upload.html')

HTML:

{% if user.is_authenticated %}
<body>
<div class="container-fluid">
<div style="float: right;" class="row">
  <div class="col-xl-3 sidenav">
    <h1 style="color: #ffffff; text-align: center">All Matches</h1><br>
    <form class="form-inline">
    <input class="form-control mr-sm-2 input-mysize" type="search" placeholder="Search" aria-label="Search">
  </form><br>
      {% for match in all_matches %}
      <li style="list-style: none ; text-align: center"><a href="{{match.url}}" target="iframe1">{{match.name}}</a></li>
      <hr class="new1">
      {% endfor %}
    </div>

  <div class="col-md-9">
  <iframe name="iframe1" width="1060" height="730" frameborder="0" allowFullScreen="true"></iframe>
  </div>
</div>
</div>
</body>
{% else %}
<meta http-equiv="refresh" content="0; url=/login" />
{% endif %}
</html>

请以我能做到的方式帮助我。

标签: djangodjango-modelsdjango-rest-frameworkdjango-viewsdjango-templates

解决方案


我找到了简单的解决方案。我必须像这样在匹配模型中添加一个 M2M 用户字段:

from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class Match(models.Model):
    name = models.CharField(max_length = 100)
    user = models.ManyToManyField(User)
    url = models.CharField(max_length = 1000)
    
    def __str__(self):
        return self.name

然后我必须过滤视图,以便每个用户只能看到从 M2M 字段分配给他的匹配项,如下所示:


from django.shortcuts import render
from .models import Match
# Create your views here.

def index(request):
    all_matches = Match.objects.filter(user=request.user)
    return render(request, 'landing.html' , {"all_matches" : all_matches})

瞧!


推荐阅读