django - How to pass context variables from multiple view functions to the same template -


i have single template serviced multiple view functions. example, read_posts() view returns posts get, add_post() view adds new post post.

i may have other post actions on same page, needing more view functions.

now, each of these view functions need pass different arguments template. e.g. each form might require different form argument passed.

what best practice in organizing multiple arguments single template multiple view functions?

as example posts.html template use:

<html>     <head>       <title>my django blog</title>     </head>     <body>         <form action="{% url 'blog:add_post' %}" method="post">              {% csrf_token %}              <p><input type="text" name="title" id="title" /></p>              <p><input type="textarea" name="text" id="text" /></p>              <input type="submit" value="submit" />         </form>         {% post in posts %}         <h1>{{ post.title }}</h1>         <h3>{{ post.pub_date }}</h3>         {{ post.text }}         {% endfor %}      </body> </html>                       

here views use:

def display_posts(request):     #all posts     posts = post.objects.all()     sorted_posts = posts.order_by('-pub_date')     context = { 'posts' : sorted_posts }     return render(request, 'blog/posts.html', context)  def add_post(request):     if request.method == 'post':         form = postform(request.post)         #return httpresponse('hello world')         if form.is_valid():             post = post()             post.title = form.cleaned_data['title']             post.text = form.cleaned_data['text']             post.pub_date = datetime.now()             post.save()             return httpresponseredirect(reverse('blog:display_posts'))         else:             form = postform() # unbound form     return render(request, "blog:display_posts") 

as may see display_posts() default when page requested, , add_post() handles http post, when new post created.

each function handling different functionality of page, , need different context variables passed template. (note used context display_posts yet)

how make sure each function sends different context page, , organize them in template?

when handle multiple forms on page, use partial templates them , %include them in main page?

thanks.


Comments