简体   繁体   English

Django:当用户返回上一页或返回登录页面时,如何重定向或断开用户连接

[英]Django: How to redirect or disconnect the user when he came back to the previous page or coming back to the login page

I thank you in advance for any help you could give to me about this question. 预先感谢您为这个问题提供的帮助。

I would like the user to be redirect automatically to another page in my Django web application in the case he click on the button in order to coming back to the last page, or when he came back to the login page again I would like to disconnect it and when he still logged and he try to access to the register page, I would to disconnect it or redirect to another page from my website. 我希望用户在单击按钮以返回到上一页时自动将其重定向到Django Web应用程序中的另一个页面,或者当他再次返回登录页面时,我想断开连接它,当他仍然登录并尝试访问注册页面时,我将其断开连接或从我的网站重定向到另一个页面。

I have already tried LoginMixin and redirect but nothing. 我已经尝试过LoginMixin和重定向,但是什么也没有。 when I am already logged and backing to the previous page I mean the login page I am still logged and I am have the login page even when I am already logged, the same I can go back to the register page but I am already logged. 当我已经登录并返回上一页时,我的意思是登录页面仍在登录,即使已经登录我也具有登录页面,同样,我可以返回注册页面,但我已经登录了。

I am using Django 2.1.7 the latest version. 我正在使用最新版本的Django 2.1.7。 So help any help will be appreciated. 因此,帮助将不胜感激。

Thank you again. 再次感谢你。

Here is my code the correct one. 这是我的正确代码。 maybe he can help anyone else. 也许他可以帮助其他人。

def login(request):

    if request.user.is_authenticated:
        return redirect('index')

    else:

        if request.method == 'POST':
            email = request.POST['email']
            password = request.POST['password']


def get_next_url():
                #request = self.request
                next_ = request.GET.get('next')
                next_post = request.POST.get('next')
                redirect_path = next_ or next_post or None
                if is_safe_url(redirect_path, request.get_host()):
                    return redirect_path
                return 'user-home'
            # def get_client_ip(request):
            #     x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
            #     if x_forwarded_for:
            #         ip = x_forwarded_for.split(',')[0]
            #     else:
            #         ip = request.META.get('REMOTE_ADDR')
            #     return ip



def get_ip_address_from_request(request):      
""" Makes the best attempt to get the client's real IP or return the loopback """
                PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', '127.')
                ip_address = ''
                x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '')
                if x_forwarded_for and ',' not in x_forwarded_for:
                    if not x_forwarded_for.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(x_forwarded_for):
                        ip_address = x_forwarded_for.strip()
                else:
                    ips = [ip.strip() for ip in x_forwarded_for.split(',')]
                    for ip in ips:
                        if ip.startswith(PRIVATE_IPS_PREFIX):
                            continue
                        elif not is_valid_ip(ip):
                            continue
                        else:
                            ip_address = ip
                            break
                if not ip_address:
                    x_real_ip = request.META.get('HTTP_X_REAL_IP', '')
                    if x_real_ip:
                        if not x_real_ip.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(x_real_ip):
                            ip_address = x_real_ip.strip()
                if not ip_address:
                    remote_addr = request.META.get('REMOTE_ADDR', '')
                    if remote_addr:
                        if not remote_addr.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(remote_addr):
                            ip_address = remote_addr.strip()
                if not ip_address:
                    ip = request.META.get('REMOTE_ADDR')
                    ip_address = ip
                return ip_address

            try:
                ip = get_ip_address_from_request(request)
                user = User.objects.get(email=email)
                if user.check_password(password) and user.is_active:
                    email = user.email
                    user = auth.authenticate(email=email, password=password)
                    auth.login(request, user)
                    alert_connection = User.objects.filter(connection_info=True)

                    if alert_connection:
                        base_url = getattr(settings, 'BASE_URL', 'http://www.dram-access.com')
                        context = {
                            'base_url': base_url,
                            'ip': ip,
                            'email': request.user.email,
                            'first_name': request.user.first_name,
                            'last_name': request.user.last_name
                            }
                        txt_ = get_template("accounts/emails/send_just_logged.txt").render(context)
                        html_ = get_template("accounts/emails/send_just_logged.html").render(context)
                        subject = 'New connection on your DreamAccess account'
                        from_email = settings.DEFAULT_FROM_EMAIL
                        recipient_list = [request.user.email] 
                        send_mail(
                            subject,
                            message=txt_,
                            from_email=from_email,
                            recipient_list=recipient_list,
                            html_message = html_,
                            fail_silently=False,
                        )

                    messages.success(request, 'You are now logged in on DreamAccess')
                    next_path = get_next_url()
                    return redirect(next_path)

                elif user.check_password(password):
                    qs = User.objects.filter(email=email)
                    if qs.exists():
                        #user email registered check active
                        not_active = qs.filter(is_active=False).exists()
                        confirm_email = EmailActivation.objects.filter(email=email, activated=False, forced_expired=False)
                        #is_confirmable = confirm_email.confirmable().exists()
                        if confirm_email and not_active:
                            return redirect('account-user-inactive')
                        elif not_active:
                            return redirect("send-reactivation-message")
                else:
                    messages.error(request, "Your password is invalid")
                    return redirect('login')
            except User.DoesNotExist:
                messages.error(request, "This username and password doesn't exist on DreamAccess")
                return redirect('login')
        else:
            return render(request, 'accounts/login.html')`

My Register page code: 我的注册页面代码:

def register(request):

if request.user.is_authenticated:
    return redirect('index')
else:
    form = RegisterForm(request.POST, request.FILES or None)
    context = {
        'form': form
        }
    if form.is_valid():
        #form.save()

        first_name = form.cleaned_data.get('first_name')
        last_name = form.cleaned_data.get('last_name')
        username = form.cleaned_data.get('username')
        email = form.cleaned_data.get('email')
        country = form.cleaned_data.get('country')
        types = form.cleaned_data.get('types')
        password = form.cleaned_data.get('password')
        password2 = form.cleaned_data.get('password2')
        phone = form.cleaned_data.get('phone')
        profile_pic = form.cleaned_data.get('profile_pic')

        new_user = User.objects.create_user(first_name, last_name, username, email, country, types, password, phone, profile_pic)

    else:
        return render(request, 'accounts/register.html', context)

Please provide your code, if you have any. 如果有的话,请提供您的代码。 On the signup page view, your code should look like this: 在注册页面视图中,您的代码应如下所示:

if request.user.is_authenticated:
    # HttpResponseRedirect('/redirectToNonRegisterPageURL/')
    ...
else:
    # Load Sign Up Form
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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