Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You'll need to pass the complete list of categories and also an index of user-selected categories to your template. You don't need to convert the <code>NewsCategory</code> queryset into a list in your view, by the way:</p> <p><strong>View</strong></p> <pre><code>categories = NewsCategory.objects.all() user_preferences = [item.id for item in Profile.preference.all()] </code></pre> <p>The <code>user_preferences</code> variable will act as a lookup index for our template.</p> <p>Then you loop through all the categories in the template, and check to see if it exists in the list of user preferences:</p> <p><strong>Template</strong></p> <pre><code>&lt;div id="c_b"&gt; {% for c in categories %} &lt;input type="checkbox" name="category[]" id="id_{{ c.category }}" value="{{ c.id }}" {% if c.id in user_preferences %}checked="checked"{% endif %} /&gt; &lt;label for="id_{{ c.id }}"&gt;{{ c.category }}&lt;/label&gt; {% endfor %} &lt;/div&gt; </code></pre> <p><strong>Update - saving user preferences</strong></p> <p>There is no hard and fast rule here. The main consideration, as far as I am concerned, would be minimising database hits. You can just clear the user preferences, like you say, and add the new ones - in fact, this is how Django's admin handles it. Just make use of Django's transaction management:</p> <pre><code>from django.db import transaction @transaction.commit_manually def add_preferences(user, preferences): user.preference.clear() for pref in preferences: user.preference.add(pref) transaction.commit() </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload