django:在同一页面中获取输入并显示输出 [英] django: taking input and showing output in the same page

查看:22
本文介绍了django:在同一页面中获取输入并显示输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Django 很陌生,正在努力做一些非常简单的事情.我有以下模型的 ModelForm:

class 查询(models.Model):user_id=models.CharField(max_length=200)查询=models.CharField(max_length=200)

我正在向用户展示一个简单的表单,它将有助于执行以下操作:

  • 用户会问一个问题
  • 问题将被处理(将生成一个数据库查询基于问题)

  • 然后查询结果应该显示在表格的正下方同一页.

这是我的 views.py 的样子:

from django.http import HttpResponse从 django.shortcuts 导入 get_object_or_404,渲染从 basicapp.models 导入 QueryForm定义索引(请求):表格=我的表格()real_form=form.getForm(请求)响应=形式.响应返回渲染(请求,'basicapp/index.html',{'形式':real_form,'响应':响应,})类 MyForm:响应=''def getForm(self,request):表单 = QueryForm(request.POST)如果 form.is_valid():response=form.cleaned_data['查询']表单.save()退货单

现在我正在尝试简单的东西,我正在获取表单查询字段中的值并尝试将其发送回页面;到目前为止我失败了.这是 index.html:

{% csrf_token %}{{ 形式 }}<p>{{响应}}</p><input type="submit" value="Submit"/></表单>

如果我能做到这一点,我认为查询的东西不会那么难.表格工作正常,数据正在保存在数据库中.提交表单后,在 index.html 中无法检索到来自 views.pyresponse 字符串.你能帮忙吗?

根据 Hoff 的回答,在 index.html 中尝试了以下操作:

{% csrf_token %}{{ 形式 }}<input type="submit" value="Submit"/></表单><div id="响应">

<脚本语言=JavaScript">$(document).ready(function() {$("#myForm").submit(function() {//捕捉表单的提交事件$.ajax({//创建一个 AJAX 调用...data: $(this).serialize(),//获取表单数据类型:$(this).attr('GET'),成功:功能(响应){//成功..$("#response").html(response);//更新 DIV}});返回假;});});

仍然没有运气:(

解决方案

views.py

def 索引(请求):问题=无如果 request.GET.get('search'):search = request.GET.get('搜索')问题 = Queries.objects.filter(query__icontains=search)name = request.GET.get('name')查询 = Queries.object.create(query=search, user_id=name)查询.save()返回渲染(请求,'basicapp/index.html',{'问题':问题,})

html

问题:<input type="text" name="search"><br/>名称:<input type="text" name="name"><br/><input type="submit" value="Submit"/></form><br/><br/>{% for question in question %}<p>{{问题}}</p>{% 结束为 %}

I am quite new to django and struggling to do something very simple. I have a ModelForm for the following model:

class Queries(models.Model):
    user_id=models.CharField(max_length=200)
    query=models.CharField(max_length=200)

And I am showing the user a simple form that will help in doing the following:

  • user will ask a question
  • The question will be processed(a database query will be generated based on the question)

  • Then the query result should be shown just beneath the form in the same page.

This is how my views.py looks like:

from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from basicapp.models import QueryForm

def index(request):
    form=MyForm()
    real_form=form.getForm(request)
    response=form.response
    return render(request,'basicapp/index.html',{
        'form': real_form,
        'response':response,
    })
class MyForm:
    response=''
    def getForm(self,request):
        form = QueryForm(request.POST)
        if form.is_valid():
            response=form.cleaned_data['query']
            form.save()
        return form

For now I am trying simple stuffs,I am taking the value in query field of the form and trying to send it back to the page;so far I am failed. This is index.html:

<form action=" " method="post">{% csrf_token %}
{{ form }}
<p>{{response}}</p>
<input type="submit" value="Submit" />
</form>

If I could do this,I think the query stuffs wont be that tough.The form is working fine,the datas are getting saved in database. Only the response string from views.py could not be retrieved inside index.html after form submission. Can you please help?

EDIT: Tried following in index.html based on Hoff's answer:

<form id="myForm" action=" " method="get">{% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>
<div id="response">
</div>
<script language="JavaScript">
    $(document).ready(function() {
        $("#myForm").submit(function() { // catch the form's submit event
            $.ajax({ // create an AJAX call...
                data: $(this).serialize(), // get the form data
                type: $(this).attr('GET'), 
                success: function(response) { // on success..
                    $("#response").html(response); // update the DIV
                }
            });
            return false;
        });
    });
</script>

Still no luck :(

解决方案

views.py

def index(request):
    questions=None
    if request.GET.get('search'):
        search = request.GET.get('search')
        questions = Queries.objects.filter(query__icontains=search)

        name = request.GET.get('name')
        query = Queries.object.create(query=search, user_id=name)
        query.save()

    return render(request, 'basicapp/index.html',{
        'questions': questions,
    })

html

<form method="GET">
    Question: <input type="text" name="search"><br/>
    Name: <input type="text" name="name"><br/>
    <input type="submit" value="Submit" />
</form><br/><br/>


{% for question in questions %}
<p>{{question}}</p>
{% endfor %}

这篇关于django:在同一页面中获取输入并显示输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆