django - 我想将匹配项分配给我在 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>
请以我能做到的方式帮助我。
解决方案
我找到了简单的解决方案。我必须像这样在匹配模型中添加一个 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})
瞧!
推荐阅读
- php - fopen 无法在没有错误的服务器上运行
- r - Power Query 或 R. 透视数据并在开始日期和结束日期之间创建缺失日期
- java - 策略设计模式和实现行为之间的差异
- reactjs - 如何让 FileInput 字段在 react-admin 3.2.3 中工作
- angular - 在 Angular 中以对象作为参数向 API 发送 Http 请求
- javascript - 如何有效地找到句子数组中字符串数组的确切个体计数?
- windows - 使用 GitLabRunner 在具有永久活动用户会话的窗口上执行 GUI 测试
- api - 在云存储提供商之间复制文件
- java - 使用 strokeOval 在画布上绘制圆圈 - 如何让它从鼠标单击网格位置扩展
- php - Illuminate\Contracts\Filesystem\Factory 不可实例化