Django request.POST.get () возвращает None - PullRequest
0 голосов
/ 25 апреля 2020

У меня проблема, и я не могу найти решение.

Я пытаюсь перенаправить на предыдущую страницу после входа в систему. Каким-то образом? Next = request.path не возвращает ничего при попытке request.POST.get () после отправки.

Это мой Html код, который направляет пользователя на страницу входа в систему, принимая request.path в качестве значения "next page after login".

{% if user.is_authenticated %}
    <button class="btn" data-toggle="modal" data-target="#inquiryModal">
      <a class="btn btn-primary border rounded-0" 
         role="button" href="#">Make an Inquiry</a>
    </button>
{% else %}
     <a class="btn btn-primary border rounded-0" role="button" 
        href="{% url 'login' %}?next={{ request.path|urlencode }}"
                        >Make An Inquiry</a>
{% endif %}

Это страница входа в систему html код.

<div class="login-clean" style="background-color: #fff;">
    <form action="{% url 'login' %}" method="POST">
        {% csrf_token %}

        <!--- ALERTS -->
        {% include 'partials/_alerts.html' %}

        <div class="form-group">
             <input class="form-control" type="email" name="email" placeholder="Email"></div>
        <div class="form-group">
             <input class="form-control" type="password" name="password" placeholder="Password">
        </div>
        <div class="form-group">
             <button class="btn btn-primary btn-block" type="submit">Log In</button>
        </div>
     </form>
</div>

Views.py file

def login(request):
    if request.method == 'POST':
        email = request.POST['email']
        password = request.POST['password']
        valuenext = request.POST.get('next')


        print(valuenext)

        user = auth.authenticate(username=email, password=password)

        # if user is found and not from listing page login and redirect to dashboard
        if user is not None and valuenext == "":
            auth.login(request, user)
            messages.success(request, 'You are now succesfully logged in')
            return redirect('dash_inquiries')

        # if user is found and from specific listing page login and redirect to the listing
        elif user is not None and valuenext != "":
            auth.login(request, user)
            print("success")
            messages.success(request, 'You are now logged in')
            return redirect(valuenext)

        else: 
            messages.error(request, 'Invalid credentials')
            return redirect('login')

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

Что я здесь не так делаю? Следующее значение передается в URL при перенаправлении на страницу входа, но я, похоже, неправильно получаю () следующее значение в моем бэкэнде, так как оно продолжает возвращать None.

Заранее спасибо.

Ответы [ 2 ]

0 голосов
/ 25 апреля 2020

Хорошо, поэтому я не убедился, что передал следующее значение в форму входа в систему, поэтому решением было добавить скрытый ввод для получения следующего значения в запросе:

<input type="hidden" name="next" value="{{ request.GET.next }}" />
0 голосов
/ 25 апреля 2020

Нажатие на следующую кнопку отправит запрос GET.

<a class="btn btn-primary border rounded-0" role="button" 
    href="{% url 'login' %}?next={{ request.path|urlencode }}">Make An Inquiry</a>

Этот запрос на получение отобразит accounts/login.html шаблон.

Вы анализируете request.POST.get('next') для POST запросы только. Но в

<form action="{% url 'login' %}" method="POST"> 

нет следующего тега form. Вам нужно выглядеть как

<form action="{% url 'login' %}next={{ next }}" method="POST">

. request.GET и добавьте его к context для ответа.

if request.method == 'POST':
    # handle POST
else:
    next = request.GET.get('next', '')
    context = {'next': next}
    return render(request, 'accounts/login.html', context=context)

А затем добавьте next в form.action.

<form action="{% url 'login' %}next={{ next }}" method="POST">
...