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 fromviews.py
could not be retrieved insideindex.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 :(
score:12
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 %}
Similar question
- django: taking input and showing output in the same page
- django: taking user input from html, processing it and showing output in the same page
- Stay on the same html page with output in django
- How to retrieve page data as input and give a custom defined Output to the user?
- Django admin - Edit parent model and related models on the same page
- Django DateTimeField show Date and Time input in the same line in admin
- Open redirect page in new tab and reopen in the same tab on multiple redirects Django
- Django generic.ListVIew: display list item's details on the same page (~ combine ListView and DetailView)
- Django - Trouble calling function in templates and return rendering the value of that function to the same page
- How do I get multiple post requests from Django and Ajax on the same page working?
score:1
Following Hoff's answer...
Add URL attribute to ajax call:
$(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'),
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?
score:3
What you need is an asynchronous post (ajax), which is easy with jQuery, see this answer for a complete solution: How to POST a django form with AJAX & jQuery
score:4
<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:
- Check if a relevant
request.POST
dict key exists or not in your view. - If the key exists, then it's a post request; add post related context variables and do post related tasks.
- 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 %}
Credit To: stackoverflow.com
Related Query
- Display a form and the output on the same page
- Add two numbers in django and output will print same on same page
- How can django sql queries use case insensitive and contains at the same time?
- Use "contains" and "iexact" at the same query in DJANGO
- Django dynamically get view url and check if its the current page
- Django and Mustache use the same syntax for template
- Saving objects and their related objects at the same time in Django
- differentiating between different post requests on the same page in Django views.py
- Generating a url with the same GET parameters as the current page in a Django template
- Render page initially and update via AJAX using the same template HTML
- How to deploy a WordPress site and Django site on the same domain?
- Django Rest Framework with multiple Viewsets and Routers for the same object
- Using both SQLAlchemy and Django ORM on the same database
- Django Rest Framework - passing Model data through a function, then posting output in a separate field in the same model
- django wizard, using form and formset in the same step
- How insert 2 different forms on the same page in Django
- How to remove the unselected item in a select and radio input in Django
- Load json data for the first time request and to display the same in Home Page
- Django custom user model doesn't show up under Authentication and Authorization in the admin page
- Is it correct to use a ViewSet and the APIView mixins on the same view in Django REST Framework?
More Query from same tag
- Django web app deploy in Azure via Visual Studio 2017
- How could I recognize private pages and public pages from QuerySets of Wagtail page?
- TypeError: cannot unpack non-iterable bool object
- Can't login to django admin despite correct superuser credentials
- Fast get all subusers of specific node in django users table
- ImportError: No module named base in html5lib
- Bootstrap4 datepickerinput calender icon is not clickable
- Cant use GenericForeignKey in django 1.8.4
- Django Form File Field disappears on form error
- Django, Redirect user to different page by user's type
- Django: Full fledge Facebook and Twitter integration (Django-Facebook, django-social-auth, django-allauth)
- Django modelformset order_by not working
- Trying to set timezone to EST in Django
- Django deployment problem in Apache/mod_wsgi. ImportError: Could not import settings 'site.settings'
- Remove element from ArrayField of PostgreSQL in Django