首页 > 解决方案 > django 模板中的按钮不会将数据放入数据库

问题描述

我有一个名为“mysite”的应用程序。我希望它执行一个python脚本,当单击按钮时,它将暂时将虚拟数据放入数据库(添加行)(最初我将从API中提取数据)但是单击按钮时没有任何反应。

网址.py

path('', views.index),

视图.py

from .fetch_data import get_data

def index(request):
    if (request.method == 'POST' and 'script' in request.POST):
        get_data()

    return render(request, 'mysite/index.html')

“mysite/templates/mysite”文件夹中的 index.html

<form method="POST" name='script'>
{% csrf_token %}    
<button type="submit" >Fetch data from source</button>
</form>

fetch_data.py

    from .models import Hosts
    import time, sys

    def get_data():
        print('here in function')
        p = Hosts(hostname="first data")
        p.save()

但是当我点击按钮时,什么也没有发生。即使成功单击按钮后,视图也应保持不变。

注意:fetch_data.py 与views.py 和urls.py 位于同一文件夹中。

标签: djangodjango-modelsdjango-templates

解决方案


试试这个可能对你有帮助

from .fetch_data import get_data

def index(request):
    if (request.method == 'POST'):
        script = get_data.objects.all()
        script.save()

    return render(request, 'mysite/index.html')

推荐阅读