Django: input input and display output on the same page

I am new to django and try my best to make 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 show the user a simple form that will help in the following:

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

  • Then the query result should be shown only under the form in the same page.

This is what my view.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 

At the moment, I'm trying to use simple things, I take the value in the form request field and try to send it back to the page until I have worked. 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 request material would not be so harsh. The form works fine, the data is saved in the database. Only the response line from views.py cannot be restored inside index.html after the form is views.py . Could you help me?

EDIT: Tried 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 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 out of luck :(

+8
django django-forms modelform
source share
4 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 %} 
+9
source share

What you need is an asynchronous post (ajax), which is easy with jQuery, see this answer for a complete solution: How to submit a django form using AJAX and jQuery

+3
source share

After Goff's answer ...

Add URL attribute for ajax call:

 $(document).ready(function() { $("#myForm").submit(function() { // catch the form submit event $.ajax({ // create an AJAX call... data: $(this).serialize(), // get the form data type: $(this).attr('GET'), url: '/URL-to-ajax-view/', success: function(response) { // on success.. $("#response").html(response); // update the DIV } }); return false; }); }); 

Some ajax handler in views.py:

 # /URL-to-ajax-view/ def ajax_get_response(request): if request.method == "GET" and request.is_ajax: form = QueryForm(request.POST or None) if form.is_valid(): form.save() return HttpResponse(form.response) raise Http404 

Tried something like that?

+1
source share
 <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 is a mail 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 a post # Example: context.update({'post_output': request.POST.get('query','')}) ... return render(request, 'index.html', context) 

Then, in the template, check if the post_output context variable post_output if it shows the result:

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


In short, the logic is this:
  • Check if the corresponding request.POST dict key exists or not.
  • If the key exists, then this is a send request; Add context variables associated with the message and complete tasks related to the message.
  • Check if any context-related context variable is available in the template, and if so, indicate the output associated with the publication.

If you do not want to show the result when the page just refreshes after publication, pass the request object to the template and perform the check as follows:

 {% if request.POST.submit and post_output %} 
+1
source share

All Articles