django: taking input and showing output in the same page

后端 未结 4 1385
Happy的楠姐
Happy的楠姐 2020-12-25 08:15

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


        
相关标签:
4条回答
  • 2020-12-25 08:46
    <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 %}
    
    0 讨论(0)
  • 2020-12-25 08:46

    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

    0 讨论(0)
  • 2020-12-25 08:49

    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?

    0 讨论(0)
  • 2020-12-25 08:54

    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 %}
    
    0 讨论(0)
提交回复
热议问题