[英]Pass URL parameters to Python
I have the following code in one of my templates. 我的模板之一中包含以下代码。
<html>
<body>
<script>
var val1 = 10;
var val2 = 20;
</script>
<a href="/generate/">Generate</a>
</body>
</html>
I wish to use the values val1 and val2 in the generate
function in the views.py file. 我希望在views.py文件的generate
函数中使用值val1和val2。 It would be something like this. 就像这样。
def generate(request):
# do something with val1 and val2
I am lost as to how I can pass these values to the function. 我不知道如何将这些值传递给函数。 What is the best practice for this, should I try to retrieve the information through URL parameters? 最佳做法是什么,我应该尝试通过URL参数检索信息吗? Or perhaps I should just remove the Javascript and do everything in Python directly in the generate()
function? 或者,也许我应该删除Javascript,然后直接在generate()
函数中使用Python做所有事情?
Thank you for your help! 谢谢您的帮助!
You need to apply HTTP methods such as GET or POST. 您需要应用HTTP方法,例如GET或POST。
use this code in view template (example - index.html
): 在视图模板中使用以下代码(示例index.html
):
<html>
<body>
<form method="post" action="/generate">
{% csrf_token %}
<input type="number" name="val1" value="10">
<input type="number" name="val2" value="20">
<input type="submit" value="generate">
</form>
</body>
</html>
and use this code in views.py
: 并在views.py
使用此代码:
def index(request):
return render_to_response('index.html', RequestContext(request))
def generate(request):
val1 = request.POST.get('val1', 0)
val2 = request.POST.get('val2', 0)
sum = val1 + val2
return HttpResponse(str(sum))
This link is helpful for you: https://docs.djangoproject.com/en/dev/topics/forms/ 该链接对您有所帮助: https : //docs.djangoproject.com/en/dev/topics/forms/
Pass the parameters using GET: 使用GET传递参数:
<html>
<body>
<a href="/generate/?val1=10&val2=20">Generate</a>
</body>
</html>
Now you can access them in view using request attribute: 现在,您可以使用request属性在视图中访问它们:
def generate(request):
if request.method == 'GET':
val1 = request.GET.get('val1')
val2 = request.GET.get('val2')
#futher code
https://docs.djangoproject.com/en/dev/ref/request-response/# https://docs.djangoproject.com/en/dev/ref/request-response/#
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.