Django - Changing order_by on click
<p>Using Django and I would like to change the order of the display of the objects on click without refreshing the page.</p>

<p>my model</p>

<pre><code>class IndexView(generic.ListView):
    template_name = 'movies/index.html'
    page_template = 'movies/all_movies.html'
    context_object_name = 'all_movies'
    model = Movie

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context.update({
            'all_genres': Genre.objects.all(),
            'our_pick': Movie.objects.get(pk=259)
        })
        return context

    def get_queryset(self):
        return Movie.objects.all()
</code></pre>

<p>And this is my <strong>index.html</strong></p>

<pre><code>&lt;menu class="menu"&gt;
   &lt;ul&gt;
     &lt;li&gt;&lt;a href="#"&gt;Newest&lt;/a&gt;&lt;/li&gt;
     &lt;li&gt;&lt;a href="#"&gt;Most Popular&lt;/a&gt;&lt;/li&gt;
   &lt;/ul&gt;
&lt;/menu&gt;
</code></pre>

<p>on clink on Newest, the query will become:</p>

<pre><code>Movie.objects.all().order_by('release_date')
</code></pre>

<p>and on click on Most popular, the query will become:</p>

<pre><code>Movie.objects.all().order_by('popularity')
</code></pre>

<p>How can I achieve that without refreshing the page? any help would be appreciated!</p>

<p>Your question seems to illustrate a misunderstanding of how front-end and back-end languages work: a click event occurs on the front-end, <em>after</em> the data has been sent from the server. The <code>order_by</code> function is run and completed <em>before</em> the request is completed. </p>

<p>To load new data from the server without reloading, you will have to send a new request in the background using AJAX. </p>

<p>This is probably <strong>not a good idea</strong>, though, since you are sending the same query set ordered in a different way. I recommend using JS or jQuery to order the list on a click event based on a <code>data</code> attribute that you can set in the list itself. For more information about how to do this, see <a href="http://stackoverflow.com/questions/21600802/jquery-sort-list-based-on-data-attribute-value">jquery sort list based on data attribute value</a>.</p>

python django