简体   繁体   中英

How can I redirect to a page depend on different user group correctly by django?

I am creating a feature to let the banned user (user without any group) go to a specific page banned_alert when they click the "post", because they are not allowed to do so. But then when I test this feature, the Chrome shows This page isn't working | the IP redirected you too many times. This page isn't working | the IP redirected you too many times. Can somebody tell me how to do it correctly? Did I miss any configuration? Below is my code snippets. Thank you for your time!

base.html: ( has_group function already works correctly somewhere else)

{% load get_group %}
{% if request.user|has_group:"mod" or request.user|has_group:"default" or user.is_staff %}
<a class="nav-link" href="/create-post">Post</a>
{% else %}
<a class="nav-link" href="/banned_alert">Post</a>
{% endif %}

banned_alert.html:

{% extends 'main/base.html' %}
{% block title %}Your account has been banned by Admin{% endblock %}
{% load crispy_forms_tags %}
{% block content %}
<h2>Please contact the Admin!</h2>
{% endblock %}

view.py

def banned_alert(request):
    return redirect('/banned_alert')

urls.py

urlpatterns = [
    path('', views.home, name='home'),
    path('home', views.home, name='home'),
    path('sign-up', views.sign_up, name='sign_up'),
    path('create-post', views.create_post, name='create_post'),
    path('banned_alert', views.banned_alert, name='banned_alert'),
]

You have a recursion:

this is your path

path('banned_alert', views.banned_alert, name='banned_alert'),

  1. User visit this banned_alert path,
  2. it redirects user to view banned_alert
  3. Which redirects user back to url banned_alert
  4. and it redirects back to view banned_alert
  5. reapeat N times (it has no ending)

best way to ban user is to create a flag in his model:

models.py

class User(AbstractUser):
    is_banned = models.BooleanField(default=False)

if you want to ban user , change user's field is_banned to true , and then in your template or view, check if user is banned or not, and do your logic according to it

By the way, in your ulrs.py you need to close paths with backslash like this path('home/', views.home, name='home'),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM