django: taking input and showing output in the same page

后端 未结 4 1403
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

    
    
    

    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 %}
    

提交回复
热议问题