首页 > 解决方案 > 将表单更改为搜索框

问题描述

这是我的表单代码,其中用户插入股票代码,输入结果显示在新页面中。到目前为止我做了什么:

模型.py

from django.db import models
from django.contrib import auth


class Child(models.Model):
    name = models.CharField(max_length=150, blank=True)

在forms.py中

from django import forms
from .models import Child

class ChildlForm(forms.ModelForm):
    class Meta:
        model = Child
        fields = ('name',)

在views.py

from django.shortcuts import render
from .forms import ChildForm
from pandas_datareader import data as wb
from yahoofinancials import YahooFinancials

# Create your views here.


def home(request):
    form = ChildForm()
    if request.method == "POST":
        form = ChildForm(request.POST)
        if form.is_valid():
            data = form.save(commit=True)
            name = data.name

            symbols = [name]
            yahoo_financials = YahooFinancials(symbols)
            new_data = pd.DataFrame()
            for s in symbols :
                new_data[s] = wb.DataReader(s, data_source ='yahoo', start = '2014-1-1')['Adj Close']

            a = new_data[s]
            b = a[-1]


            context={
            'name':name,
            'b':b,}

        else:
            form = ChildForm()
            return render(request,'main/index.html',{'form':form})
        return render(request,'main/index2.html',context)


    return render(request,'main/index.html',{'form':form})

index.html文件_

<form method="POST">
    {{ form }}
    {% csrf_token %}
    <input class="form-control mr-sm-2" type="text">
    <button type="submit">OK</button>
  </form>

我意识到表单方法有局限性,并将名称放在看起来很难看的输入框前面。

我试图用搜索框在index2.html文件中构建 serach 框,但它不起作用:

<nav class="navbar navbar-default">
        <div class="container-fluid">
            <form id="searchbox" method="get" autocomplete="off" class="navbar-form navbar-left" role="search">
                <input name='q' type="text" type="text" class="form-control" placeholder="Search" />
                <button id="button-submit" type="submit" value=" " class="btn btn-default" />
            </form>
            </div>
    </nav>

我很困惑我应该如何将表单与搜索框连接起来,甚至应该连接。在这种情况下我应该怎么做才能将搜索框中的数据转换为索引并在下一页中使用。我还希望在下一页保留搜索框,以便用户不必返回上一页来查找新符号。

将不胜感激任何帮助的建议。

标签: pythondjangosearch

解决方案


推荐阅读