[英]Assign objects to specific user in django?
嘗試使我的matches.html頁面顯示特定於用戶的時間表數據,但是當我登錄另一個用戶時,以前的用戶數據仍然存在。 有沒有一種方法可以使時間表數據分配給用戶登錄。
class timetablesetup(models.Model):
module = models.CharField(max_length=150)
day = models.CharField(max_length=100)
time = models.IntegerField()
location = models.CharField(max_length=100)
def __str__(self):
return self.module
多數民眾贊成在我的models.py,這是意見
def matches(request, user):
entrys = timetablesetup.objects.all()
context = {
'entrys': entrys
}
return render(request, 'timetableMatch/matches.html', context)
def add_entry(request):
return render(request, 'timetableMatch/add_entry.html')
def delete(request, id):
entrys = timetablesetup.objects.get(pk=id)
entrys.delete()
return redirect('/timetableMatch')
def edit(request, id):
entrys = timetablesetup.objects.get(pk=id)
context = {
'entrys': entrys
}
return render(request, 'timetableMatch/edit.html', context)
def update(request, id):
entrys = timetablesetup.objects.get(pk=id)
entrys.module = request.GET['module']
entrys.day = request.GET['day']
entrys.time = request.GET['time']
entrys.location = request.GET['location']
try:
entrys.save()
except Exception:
return redirect('/errorpage')
else:
return redirect('/timetableMatch')
這是我的比賽頁面,用於查看時間表數據
<div class="container"><br>
<h2>TimetableMatch</h2>
<hr>
<table class="table table-dark">
<thead>
<tr>
<th>Modules</th>
<th>Day</th>
<th>Time</th>
<th>Location</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for entry in entrys %}
<tr>
<td>{{ entry.module }}</td>
<td>{{ entry.day }}</td>
<td>{{ entry.time }}</td>
<td>{{ entry.location }}</td>
<td><a class="btn btn-info" href="../edit/{{ entry.id }}">Edit</a>
<a class="btn btn-danger" href="../delete/{{ entry.id }}">Delete</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
您應該使用ForeignKey將每個TimeTableSetup對象鏈接到數據庫中的User,然后在Matchs視圖中進行過濾以確保顯示給定用戶的時間表:
class timetablesetup(models.Model):
module = models.CharField(max_length=150)
day = models.CharField(max_length=100)
time = models.IntegerField()
location = models.CharField(max_length=100)
user = models.ForeignKey(<POINT TO YOUR USER MODEL HERE>)
def __str__(self):
return self.module
def matches(request, user):
# Get the user whose entries you want to show here
# E.g., user = User.objects.get(id=3)
user = <GET THE USER HERE>
# Filter entrys to only those assigned to a certain user
entrys = timetablesetup.objects.filter(user=user)
context = {
'entrys': entrys
}
return render(request, 'timetableMatch/matches.html', context)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.