如何从中间件文件的reason
模型中将UserBanning
传递到banned.html?几乎所有东西都可以正常工作,但是我似乎无法从模型中获得reason
并无法在模板banned.html
中显示,而且不确定方式,因此只要深入学习中间件,任何帮助都将是惊人的。我应该改用process_request()
吗?
谢谢
models.py:
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
class UserBanning(models.Model):
user = models.ForeignKey(User, verbose_name="Username", help_text="Choose Username", on_delete=models.CASCADE)
ban = models.BooleanField(default=True, verbose_name="Ban", help_text="Users Bans")
reason = models.CharField(max_length=500, blank=True)
class Meta:
verbose_name_plural = "User Banning"
ordering = ('user',)
def __str__(self):
return f"{self.user}"
middleware.py:
from .models import UserBanning
from django.shortcuts import render
class BanManagement():
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
banned = UserBanning.objects.all()
context = {
'banned': banned,
}
if(banned.filter(ban=True, user_id=request.user.id)):
return render(request, "account/banned.html", context)
else:
response = self.get_response(request)
return response
banned.html:
{% extends "base.html" %}
{% block content %}
<p>Your account has been banned. Reason: {{ banned.reason }}</p>
{% endblock content %}
答案 0 :(得分:0)
您快完成了。剩下的问题是,您需要在设置filter
之前在request.user.id
上context
,以便上下文仅包含此特定用户的禁令。像这样:
banned = UserBanning.objects.filter(ban=True, user=request.user)
if banned:
context = {'banned': banned[0]}
return render(request, "account/banned.html", context)
else: