Search code examples
djangotemplatesmiddleware

My Django Middleware Isn't Working The Way It Should


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?

Thanks

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 %}

Solution

  • 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: