代码之家  ›  专栏  ›  技术社区  ›  Blue

从Django中的输入字段获取用户输入

  •  0
  • Blue  · 技术社区  · 2 年前

    我要做的是获取用户输入,然后将其附加到HTML中,

    {'rawText': None}
    

    我将获取输入,并将其传递给我编写的python模块,然后将结果也附加到HTML中,就像messenger一样,它对python仍然是新的,django对为什么我在控制台中没有得到任何文本感到困惑。

    from django.shortcuts import redirect, render
    from django.shortcuts import HttpResponse
    from .forms import messageForm
    from .main import get_weather, take_user_input
    
    
    def home(request):
        form = messageForm()
    
        # Get the message to display to view.
        if request.method == "POST":
            rawText = request.GET.get('textInput')
            context = {'rawText': rawText}
        print(context)
        return render(request, 'home.html', {'form': form})
    

        from django import forms
        
        
        class messageForm(forms.Form):
            message = forms.CharField(max_length=1000)
    

    home.html:

    {% extends 'base.html'%}
    {% load static %}
    
    {% block content %}
        <h2>Blue's Chatbot</h2>
        <div>
            <div id="chatbox">
                <p class="botText"><span>Hi! Let's get to chatting.</span></p>
            </div>
            <div id="userInput">
            <form type="text" id="textInput" action="" method="POST" novalidate>
                {% csrf_token %}
                {{ form }}
                <input id="buttonInput" type="submit" value="Send">
                </form>
            </div>
    
    {% endblock %}
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   Ashish Ranjan    2 年前

    您正在使用POST方法将数据发送到服务器,因此您应该从中获取数据 POST 字典无法获取:

    request.POST.get('textInput', '') # instead of request.GET.get('textInput', '')