Note that there are some explanatory texts on larger screens.

plurals
  1. POA help in concept and a database query question (Django/Python)
    text
    copied!<p>I am trying to build a kind of news website for learning purposes. </p> <pre><code>class NewsCategory(models.Model): category = models.CharField(max_length=50) </code></pre> <p>Note: A category can be Soccer, Tennis, business ... User can register to different news category. This choice will be saved in their preferences.</p> <pre><code>class Profile(models.Model): user = models.ForeignKey(User, unique=True) gender = models.CharField(max_length=1,blank=True) preference = models.ManyToManyField(NewsCategory) </code></pre> <p>I am currently stuck on how to update the preference list of each user (the list that specifies in which categories he is interested in.)</p> <p><strong>View:</strong></p> <pre><code>category = [(item.category) for item in NewsCategory.objects.all()] </code></pre> <p>and then I am sending the <code>category</code> to the template below</p> <p><strong>template:</strong></p> <pre><code>&lt;div id="c_b"&gt; {% for c in category %} &lt;input type="checkbox" name="category[]" value="{{c}}"&gt; &lt;label for="{{c}}"&gt;{{c}}&lt;/label&gt; {% endfor %} &lt;/div&gt; </code></pre> <p><strong>Questions:</strong></p> <ol> <li><p>What is the best way to add the checked tag next to the checkboxes that are already saved in the user's preference when I display the template. </p> <p>I though of getting all the preferences users are registered for: <code>saved_preference = user.preference.all()</code> and then checking for each item in <code>category</code> if it is in <code>saved_preference</code> </p> <p>I am also blanking out on the way to actually write that into code, and whether this should be done in the view or the template.</p></li> <li><p>What is a good way to update the user preference list?</p> <p>I was planning on running <code>user.preference.clear()</code> and then going through every item in the submitted form and running <code>user.preference.add(the_new_preference)</code></p></li> </ol>
 

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