代码之家  ›  专栏  ›  技术社区  ›  M.K

在django中不获取窗体的值

  •  0
  • M.K  · 技术社区  · 7 年前

    在django中,我想打开一个url(这是由用户在表单中发布的),在用url点击submit按钮(表单的)之后,获取数据(url)并用它做一些事情(在视图中打印)。

    我只有一个功能 views.py 文件,所以我想我的主要问题是我应该有两个。但我真的不知道该怎么解决,不过我试过了。

    我的表格是这个:

    <html>
        <head>
            <title>
                Practica Django
            </title>
    
        </head>
    
            <form method="POST" action="" id = "loginForm">
                   {% csrf_token %}
                <input type="text" name="text" id= "text" value= '{% if submitbutton == "Submit" %} {{ firstname }} {% endif %}' maxlength="100"/>
                <input type="reset" name="Reset" id = "Reset" value="Reset" />
                <input type="Submit" name="Submit" id = "Submit" value="Submit" />
    
                {% if submitbutton == "Submit"  %}
    
                <h1 id = 4 name="resultado2"> {{ type }}</h1>
            {% endif %}
    
            </form>
    
    </html>
    

    在我看来:

    def vistaFormulario(request,):
        text = request.POST.get('text')
        submitbutton = request.POST.get('Submit')
        m = str(text)
        print(m)
        print(text)
    
        # Descarga el contenido del HTML
        with urllib.request.urlopen('http://www.elmundo.es/espana/2018/06/05/5b162c3b468aebd9678b4695.html') as response:
            page = response.read()
        soup = BeautifulSoup(page, 'html.parser')
        p = soup.find_all('p')
    

    所以它还在继续。但我需要打开那个网址!但是无论用户在表单中写了什么,都可以按下输入按钮!

    如你所见,我有两个 prints ,只是看看这些值有什么值。他们在输入东西并按下输入按钮之前没有,在按下它之后,他们有你写的东西。

    我想要的是在这个方法中得到我在按钮中输入的任何东西 从一开始 . 我不明白他们为什么没有。我想得到值,然后打印出来。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Peter Mortensen icecrime    6 年前

    所以,您的问题是,您需要调用Beautiful Soup,但当用户最初加载页面并且没有提交表单时,您不需要这样做。

    最简单的解决方案是将调用 bs 变成一个 if 只有当你 POST :

    # Define these so that they have a value to be called in the template
    text = submitbutton = ''
    if request.method == 'POST':
        text = request.POST.get('text')
        submitbutton = request.POST.get('Submit')
        m = str(text)
        print(m)
        print(text)
    
        # Descarga el contenido del HTML
        with urllib.request.urlopen('http://www.elmundo.es/espana/2018/06/05/5b162c3b468aebd9678b4695.html') as response:
           page = response.read()
       soup = BeautifulSoup(page, 'html.parser')
       p = soup.find_all('p')
    
    # This needs to be outside your 'if' clause, so that the page will render if the method isn't POST
    context = {'text': text,
               'submitbutton': submitbutton,
               'type':q1}
    
    return render(request, 'form/form.html', context)
    

    从你的样本来看,我不确定 qt 得到定义或获取捕获 submitbutton ,但这或多或少会起作用。