Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

python - Autofill Django signup page with automatically generated password

I created a simple page for staff members that adds users by entering a username and password, very similar to the way users are added in the admin page. How can the password field be automatically filled with a random password instead of staff members having to manually enter one in?

I have seen a method that sends the user a password-reset email, allowing them to enter their own password. This method however doesn't suit our needs.

Please take it step by step as I am still new to this language.

Any help is much appreciated!

question from:https://stackoverflow.com/questions/65646677/autofill-django-signup-page-with-automatically-generated-password

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you can do is generate a random string and pass it to the password input in your form like this:

views.py

import random
import string

def register_new_user(request):
    letters = string.ascii_lowercase
    password = ''.join(random.choice(letters) for i in range(10))
    if request.method == 'POST':
        form = SignupForm(request.POST) # your signup form class
        if form.is_valid():
            user.save()
            return redirect('home') # redirect to a valid page
    else:
        form = SignupForm()
    return render(request, 'register_new_user.html' {'form': form, 
                                                     'password': password})

Then in your template pass the password inside your password input field value attribute:

register_new_user.html

<form method="post">
    {% csrf_token %}
    <input type="text" name="username">
    <input type="password" name="password1" value="{{ password }}">
    <input type="password" name="password2" value="{{ password }}">
    <button type="submit">Submit</button>
</form>

This way each time a user accesses your register_new_user view the password fields will be prepopulated with random string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...