Target:
Create a form with two buttons with different actions for my ddnames.com project. Display the result on the same page.
urls.py:
urlpatterns = [ path('', views.index, name='index'), path('regresult', views.regresult, name='regresult'), path('regget', views.regget, name='regget'), path('getresult', views.getresult, name='getresult'), path('profile', views.profile, name='profile'), path('profileresult', views.profileresult, name='profileresult'), path('addresult', views.addresult, name='addresult'), path('delresult', views.delresult, name='delresult'), ]
In views.py create 3 functions:
Blank result. Only form view.
def regget(request): """Homepage""" reslogin = '' res = '' jwtkeyvar = '' context = {'reslogin': reslogin, 'jwtkeyvar': jwtkeyvar, 'res': res} return render(request, 'webdnss/regget.html', context)
Handling a registration request
def regresult(request): email = request.GET['email'] password = request.GET['pass'] dictToSend = {'email': email, 'password': password} resp = requests.post('http://136.244.82.142:8000/register', json=dictToSend) if str("406") in str(resp): res = f'Wrong data {resp.json()}' elif str("201") in str(resp): res = 'Congrats!\n' respjs = resp.json() for key, value in respjs.items(): res = res + f"{key} : {value}\n" context = {'res': res} return render(request, 'webdnss/regget.html', context)
Handling an API request
def getresult(request): email = request.GET['email'] password = request.GET['pass'] dataToSend = {'username': email, 'password': password} resp = requests.post('http://136.244.82.142:8000/login', data=dataToSend) reslogin = '' jwtkeyvar = '' if str("422") in str(resp): reslogin = f'Wrong data {resp.json()}' elif str("200") in str(resp): reslogin = 'Congrats!\n' respjs = resp.json() for key, value in respjs.items(): reslogin = reslogin + f"{key} : {value}\n" jwtkeyvar = respjs['access_token'] context = {'reslogin': reslogin, 'jwtkeyvar': jwtkeyvar} return render(request, 'webdnss/regget.html', context)
Template code:
<div class="form-group"> <form> <input type="text" name="email" placeholder="e-mail"><br><br> <input type="text" name="pass" placeholder="password"><br><br> <input type="submit" value="Register" formaction="regresult"> <input type="submit" value="Get API" formaction="getresult"> </form> </div> <div> {{ res|linebreaks }} </div> <div> {{ reslogin|linebreaks }}{{ jwtkeyvar }} </div>