我的Django中间件无法正常工作 [英] My Django Middleware Isn't Working The Way It Should
问题描述
如何将中间件文件中的reason
从UserBanning
模型传递到banned.html?几乎所有东西都可以正常工作,但是我似乎无法从模型中获取reason
并以模板banned.html
的形式显示,而且不确定方式,因此只要深入学习中间件,任何帮助都将是惊人的.我应该改用process_request()
吗?
How do I go about passing the reason
to banned.html from the UserBanning
model from the middleware file? Almost everything works but I can't seem to get the reason
from the model to display in the template banned.html
and im unsure way so any help will be amazing just got into learning about middleware. Should I be using process_request()
instead?
谢谢
models.py:
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:
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:
banned.html:
{% extends "base.html" %}
{% block content %}
<p>Your account has been banned. Reason: {{ banned.reason }}</p>
{% endblock content %}
推荐答案
您快完成了.剩下的问题是,在设置context
之前,您需要在request.user.id
上的filter
,以便上下文仅包含此特定用户的禁令.像这样:
You're almost done. The remaining problem is that you need to filter
on request.user.id
before you set the context
, in order for the context to contain this specific user's ban only. Something like:
banned = UserBanning.objects.filter(ban=True, user=request.user)
if banned:
context = {'banned': banned[0]}
return render(request, "account/banned.html", context)
else:
这篇关于我的Django中间件无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!