简体   繁体   中英

how to get username from login form, when reset password link is clicked django

I am trying to get the username from my login form when the reset password link has been pressed.

view.py

def ResetPassword(request):

if request.method == 'POST':
    username = request.Post.get['login_username']
    if username:
        #send password reset link via email 
    else:
        #if username is empty search for your account 
        return render(request, 'accounts/forms/email_search.html',{})

forms.html

 <form class="navbar-form navbar" method="POST"action="{% url 'login' %}">
        {% csrf_token %}

        <div class="form-group">
           {{ form.login_username }}
        </div>
        <div class="form-group">
           {{ form.login_password }}
        </div>
        <button type="submit" id="loginBtn" class="btn btn-default">Submit</button>
        <br>
       <a href="{% url 'ResetPassword' %}">Reset Password</a>
      </form>

First of all, the request object has not attribute Post , but POST .

So, it should be either

# use this if you're sure that login_username will always be passed 
`username = request.POST['login_username']`

or

# use this and in case login_username fails, then an empty string is returned
`username = request.POST.get('login_username', '')`.

Now, to your problem. The form has a submit input only for the login view. The change password button is just a plain link. Thus, when you click on it you make a GET request to the ResetPassword view (by the way, you should rename it to reset_password , it's the Python way), without any arguments passed.

To fix this, you must remove this link from inside the form. Then you have to create the template for the ResetPassword view, say reset_password.html and inside there create another form (with only the username field required) that will POST to ResetPassword view.

For example:

<!-- reset_password.html -->

<form class="navbar-form navbar" method="POST" action="{% url 'ResetPassword' %}">{% csrf_token %}
    <div class="form-group">
        <input type="text" name="login_username" required />
    </div>
    <button type="submit" id="reset-pwd-btn" class="btn btn-default">Reset Password</button>
</form>

And last:

# ResetPassword.py    

def ResetPassword(request):
    if request.method == 'POST':
        # login_username is the same as the input's name
        username = request.POST.get('login_username')
        if username:
            # send password reset link via email
        else:
            # if username is empty search for your account
        return render(request, 'accounts/forms/email_search.html', {})
    return render(request, 'accounts/forms/reset_password.html', {})

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