Tom
Tom

Reputation: 1468

How can I deactivate registration if the user is logged in?

I have got a website with a user registration and login. Both is working fine, but the registration page can still be accessed when the user is logged in. Maybe there is something like a @logout_required decorator I can wrap around the registration view?

Upvotes: 0

Views: 855

Answers (4)

sagar_v_p
sagar_v_p

Reputation: 66

You can create custom decorator for that which will check if the request user is already logged in or not if yes then redirect to home. Something like this.

def guest_user_only(view_func):
    def wrapped_view(request, *args, **kwargs):
        if request.user.is_authenticated:
            return redirect('home')
        return view_func(request, *args, **kwargs)
    return wrapped_view

@guest_user_only
def register(request):
    # your registration logic
    

Upvotes: 0

hendrikschneider
hendrikschneider

Reputation: 1846

You can solve this by using the user_passes_test decorator: https://docs.djangoproject.com/en/2.2/topics/auth/default/#django.contrib.auth.decorators.user_passes_test

from django.contrib.auth.decorators import user_passes_test

def not_logged_in(user):
  return not user.is_authenticated

@user_passes_test(not_logged_in)
def my_view(request):
  #do stuff

Upvotes: 0

JimShapedCoding
JimShapedCoding

Reputation: 917

Im assuming that you have a HTML file with a navbar on it to explain what needs to be done:

You can put this code in your template file in order to achieve this goal:


 <nav>
    <div class="nav-wrapper">
      <a href="/" class="brand-logo">Name</a>
      <ul id="nav-mobile" class="right hide-on-med-and-down">

        {% if user.is_authenticated %}
          <li>
             <a href="/">logout</a>
         </li>

        {% else %}
            <li>
            <a href="/login">Login</a>
            </li>

            <li>
            <a href="/">Register</a>
            </li>
          {% endif %}
      </ul>
    </div>
  </nav>

Upvotes: 0

Pedram
Pedram

Reputation: 3920

It's simple. In your registration view, just add a simple if statement to check whether the user has logged in or not.

def registration(request):
    if request.user.is_authenticated:
        #prevent user registration
        #...

you can use the same solution for CBVs (using self.request.user.is_authenticated).

or if you wish to do that in your template (for example, prevent the logged in user from viewing the registration form):

{% if not request.user.is_authenticated %}
    ...
{% endif %}

Upvotes: 0

Related Questions