Sunday, 15 March 2015

html - Filters and for loops in Django -


I'm sorry if this is a clear question, I'm new to Django and Python. I am working on a small blog application The following code retrieves all the posts from my database. I do not want to display them all within the main page. I just need three of all I believe that it is done for loop and some type of filter according to the document.

views.py

  def all (request): allPosts = Post.objects.all () reference = {'Mail': allPosts } Templates = "home.html" submission of references (request, template, reference)  

Home HTML

  & lt; Div class = "sidebar-module" & gt; & Lt; H4 & gt; Archive & lt; / H4 & gt; & Lt; Ol class = "list-volatile" & gt; {% For single post to%} 
  • gt; & Lt; A href = "#" & gt; {{Single.post.title}} & lt; / A & gt; & Lt; / Li & gt; {% Endfor%} & lt; / Ol & gt; & Lt; / Div & gt;
  • You are looking for only 3 posts, so there is no need to drag everyone The entries will be enough, the following:

      def All (request): "" "Only three posts to use one piece operation." "" All posts = posts.Objects. [: 3] Reference = {'Post': All Post} Templates = "home.html" Submitting Returns (Request, Template, Context)  

    You can find more in official documents : If you need filtered results, use the same concept, but apply your filter:

    On the other hand if you are going to use them all on one post, but only one 3 different parts from the same set (a sidebar, etc.), Micro you can get them as my original post, and then loops inside templates:

      & lt; Div class = "sidebar-module" & gt; & Lt; H4 & gt; Archive & lt; / H4 & gt; & Lt; Ol class = "list-volatile" & gt; {% For single post} Slice: ": 3"%} 
  • gt; & Lt; A href = "#" & gt; {{Single.post.title}} & lt; / A & gt; & Lt; / Li & gt; {% Endfor%} & lt; / Ol & gt; & Lt; / Div & gt;
  • The above will result in a new query, though be careful, if you are facing load problems, it would be better to evaluate your query, list it Be sure to use and evaluate the query:

      DF All (Request): "" "Before evaluating this template," Billo "evaluates the query. Before doing (eg ) "All posts = list (post.objects.php) reference = {'postal': all post} template =" home.html "submission of return (request, template, reference) )  

    You can find more information about the evaluation here:


    No comments:

    Post a Comment