I wrote a password generator with a checkbox in the template. I also have an if statment in the template that checks if the boolean from the views (which looks for the boolean for the characters like are there digits or symbols allowed in the password) is true or false and sets the checkbox checked or unchecked to prevent that the box unchecks after submitting the form. Now I have a really weird thing if I check the box for digits every box checks and if I uncheck it everybox unchecks, just the box not the real boolean.
This is my code:
<form method="get" action="{% url 'home:passwordgenerator' %}">
<div class="fake_input">
<p class="fake_input_text">{{ password }}</p>
</div>
<span class="fake_input_l">Length:</span> <select class="fake_input_drop" name="length">
<option value="8" {% if length == 8 %}selected{% endif %}>8</option>
<option value="10" {% if length == 10 %}selected{% endif %}>10</option>
<option value="12" {% if length == 12 %}selected{% endif %}>12</option>
<option value="14" {% if length == 14 %}selected{% endif %}>14</option>
<option value="16" {% if length == 16 %}selected{% endif %}>16</option>
<option value="18" {% if length == 18 %}selected{% endif %}>18</option>
<option value="20" {% if length == 20 %}selected{% endif %} >20</option>
</select>
<span class="fake_input_l">
Alphabet Letters: <input type="checkbox" name="alphabets" {% if alphabets_b == True %} checked {% endif %}>
Digits: <input type="checkbox" name="digits" {% if digits_b == True %} checked {% endif %}>
Special Characters: <input type="checkbox" name="special_characters" {% if special_characters_b == True %} checked {% endif %}>
</span>
<button type="submit" value="Generate Password" class="fake_input_button">Generate</button>
</form>
views.py
def view_passwordgenerator(request):
alphabets_b = bool(request.GET.get('alphabets'))
digits_b = bool(request.GET.get('digits'))
special_characters_b = bool(request.GET.get('special_characters'))
alphabets = string.ascii_letters*alphabets_b
digits = string.digits*digits_b
special_characters = "!@#$%^&*()"*special_characters_b
characters = alphabets + digits + special_characters
if 'length' in request.GET:
length = int(request.GET.get('length'))
password = ''
for i in range(length):
password+=random.choice(characters)
pyperclip.copy(password)
pyperclip.paste()
messages.info(request, 'The password was copied to your clipboard')
username = request.user.username
context = {'password': password, 'length': length, 'username': username, 'digits_b': digits_b, 'alphabets_b': alphabets_b, 'special_characters_b': special_characters_b}
return render(request, 'home/passwordgenerator.html', context)
username = request.user.username
hs = {'username': username}
return render(request, 'home/passwordgenerator.html', hs)
How can I code it correctly so that the box stays as it was before submitting the form
Thanks for your help!