Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: taking input and showing output in the same page

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 :(

like image 842
Munim Avatar asked Feb 12 '13 16:02

Munim


People also ask

How to display result in same page in Django?

If you want the form submitted to the same page that the form is on, then all you have to do is set the action attribute equal to null (""). So below, we have a form in which the action attribute is set equal to "". Therefore, the form results, based on how you program it, stays on the same page.

What is Is_valid () do in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute. Let's see an example that takes user input and validate input as well.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

How to use get and post in Django?

GET and POSTDjango's login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response. GET , by contrast, bundles the submitted data into a string, and uses this to compose a URL.


2 Answers

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 %}
like image 97
catherine Avatar answered Oct 19 '22 19:10

catherine


<input type="text" name="query" />
<input type="submit" name="submit" value="Submit" />

you can check if the form was submitted or not (i.e if it's a post request or not):

if 'submit' in request.POST: #you could use 'query' instead of 'submit' too
    # do post related task
    # add context variables to render post output
    # add another context variable to indicate if it's a post
    # Example:
    context.update({'post_output': request.POST.get('query','')})
...
return render(request, 'index.html', context)

Then in the template, check if context variable post_output exists, if it does show the output:

{% if post_output %}
    Output: {{ post_output }}
{% endif %}


In short, the logic is:
  1. Check if a relevant request.POST dict key exists or not in your view.
  2. If the key exists, then it's a post request; add post related context variables and do post related tasks.
  3. Check if any post related context variable is available in the template and if it does, show post related output.

If you don't want to show the output when the page is simply refreshed after a post, pass the request object to the template and do a check like this:

{% if request.POST.submit and post_output %}
like image 24
Jahid Avatar answered Oct 19 '22 18:10

Jahid