简体   繁体   中英

How to pass value entered in textbox to flask in text format from django?

I am a beginner in django and flask. I want to pass the value entered in textbox from django to flask.

views.py

from django.shortcuts import render
import requests

# Create your views here.

def form(request):
    return render(request,'hello/index.html')

html file

<!DOCTYPE html>
<html>
<body>


  <form action="output">
    
    Enter name: <br/>
    <input type="text" name="name"> <br/>
  
    <input type="submit" ><br/>
  
</form>
  
</body>
</html>

flask

app = Flask(__name__)

@app.route('/')
def index():
     
     return "hello" 
     
if __name__ == '__main__':
    app.run(debug=True)

In the flask i should get the values entered in django textbox....

change form tag in html as:

<form method="GET" action="output">

change urlpatterns in urls.py as:

path('output', views.output ,name ='output'),

add the following in your views.py:

def output(request):
    data = request.GET['name']
    return render(request, 'hello/**any template**.html',{'data' : data})

this will pass a variable data to your index.html Now you can use that in you any of templates with jinja.

First have a look at Django forms https://docs.djangoproject.com/en/3.1/topics/forms/#building-a-form . You'll then do not have to parse anything from you request, Django will to that for you.

Secondly have a look at https://flask-restful.readthedocs.io/en/latest/ with allows you to build a Webinterface.

Then you can use a Http POST request to send your data from Django to Flask, see https://stackoverflow.com/a/11324941/876847

This should loosely couple your apps so that they can run seperately

I have found a solution for the question, but I want to know whether there is any other way to pass data.

views.py

from django.shortcuts import render
import requests

# Create your views here.

def form(request):
    return render(request,'hello/index.html')

def output(request):
    name1=request.GET["name"]
    if not name1:
        name1=0
    response = requests.get('http://127.0.0.1:5000/'+str(name1)).json()
    #name = response.text
    return render(request, 'hello/index.html', {'out': response['out']})

html file

<!DOCTYPE html>
<html>
<body>


  <form action="output" method="GET">
    
    Enter name: <br/>
    <input type="text" name="name"> <br/>
  
    <input type="submit" ><br/>
  
</form>
<div>
  {{out}}
</div>
  
</body>
</html>

flask file

from flask import Flask,jsonify
app = Flask(__name__)
@app.route('/<name>',methods=['GET'])
def index(name):
     return jsonify({'out' : "Hello"+  " "+str(name)})
if __name__ == '__main__':
    app.run(debug=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM