I am working with Python Django and I have this really simple form, consisting of a button and an input field. The problem is that the input field is for some reason cleared after I submit the form. So How can I prevent it from clearing?
This is my python file:
def index(request):
# print(f"its me {os.getcwd()}")
txt = request.GET.get("some_txt")
if (request.GET.get('mybtn')):
print(f"THIS IS THE TEXT VALUE: {txt}")
else:
print("Has not been clicked")
return render(request, "main/index.html")
This is the HTML file:
<form action="#" method="get">
{% csrf_token %}
<input type="text" name="some_txt">
<button type="submit" value="mybtn" name="mybtn">Submit</button>
</form>
CodePudding user response:
You each time render a new form, so if you want to populate the form with the old data, you pass it to the template:
def index(request):
txt = request.GET.get('some_txt', '')
if (request.GET.get('mybtn')):
print(f'THIS IS THE TEXT VALUE: {txt}')
else:
print('Has not been clicked')
return render(request, 'main/index.html', {'txt': txt})
and in the the form, you use that as value:
<form action="" method="get">
<input type="text" name="some_txt" value="{{ txt }}">
<button type="submit" value="mybtn" name="mybtn">Submit</button>
</form>
or with a clear function:
def index(request):
txt = request.GET.get('some_txt', '')
if request.GET.get('mybtn') == 'mybtn2':
txt = ''
else if request.GET.get('mybtn'):
print(f'THIS IS THE TEXT VALUE: {txt}')
else:
print('Has not been clicked')
return render(request, 'main/index.html', {'txt': txt})
and at the HTML side we thus work with a second button:
<form action="" method="get">
<input type="text" name="some_txt" value="{{ txt }}">
<button type="submit" value="mybtn" name="mybtn">Submit</button>
<button type="submit" value="mybtn2" name="mybtn">Reset</button>
</form>