Reputation: 175
I have a function in views.py
that generate random characters, then the generated characters gets passed to the template in index
view. In the template I have change
button that should generate a new random characters but it doesn't do that. It changes whatever value in the field to the generated characters already passed to the template.
Here in the template btn1
should change the default {{ random }}
value to a new value every time it gets clicked.
index.html
<form method="POST">
<div class="input-group">
<input type="text" name="name" id="name" class="form-control" value="{{ random }}" onclick="this.select()" readonly="readonly">
<div class="input-group-btn">
<button type="submit" id="btn1" class="btn btn-default" onClick="document.getElementById('name').value='{{ random }}'">Change</button>
<button type="submit" class="btn btn-default">Find</button>
</div>
</div>
</form>
views.py
def generate(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@csrf_exempt
def index(request):
random = generate()
if request.method == 'POST':
form = NamesForm(request.POST)
if form.is_valid():
name = request.POST.get('name')
return redirect(checkingNames, name=name)
else:
form = NamesForm()
return render(request, 'index.html', {'form': form, 'random': random})
Upvotes: 1
Views: 2073
Reputation: 78
You should use javascript to make changes on page async. You have 2 ways.
If generating is going to be safe use AJAX. On click you should send ajax-request to server, which will give you new random for some data
If it's not going to be safe(as in example) you can generate random string just by javascript. For example, from here
Upvotes: 1