1๐
What Iโd do would be to get all the userโs current scores up front, create a dictionary mapping exercise to score, then add the score as an attribute of each exercise. Something like:
user_scores = request.user.score_set.all()
score_dict = dict((sc.exo_id, sc.score) for sc in user_scores)
exos = Exercise.objects.all()
for ex in exos:
ex.current_user_score = score_dict.get(ex.id)
Now each exercise in exos
has a current_user_score
attribute, which is the current userโs score for that exercise (or None).
1๐
django.contrib.auth
has a context processor that adds a user
variable to the template context, referencing the current user. This can enable you to get all scores for the current user, then you can create a template filter that returns the score for a particular exercise.
In a file named exercises.py
within a templatetags
package.
[Put the package in the folder of one of your apps in INSTALLED_APPS
. Remember templatetags
must be a valid Python package ie. with an __init__.py
]
from django.template import Library
register = Library()
@register.filter
def score_for_exercise(scores, exercise):
s = scores.filter(exo=exercise)
if s:
return s[0].score
return None
In the template:
{% load exercises %}
{% with user.score_set.all as user_scores %}
<ul>
{% for exo in exos %}
{% with user_scores|score_for_exercise:exo as score %}
<li>{{ exo }}{% if score %} - {{score}}{% endif %}</li>
{% endwith %}
{% endfor %}
</ul>
{% endwith %}
- [Answered ]-Django โ Use signals to refresh another model's fields
- [Answered ]-How to toggle glyphicon icon on toggle of a span in django templates
- [Answered ]-Is it possible to use both cheaper and emperor with uWSGI
- [Answered ]-How to escape quotes when setting a javascript string to the value propagated from a Django variable?
- [Answered ]-ModelForm view not saving or
0๐
Maybe you can add an attribute to your Exercise
:
class Exercise(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
def user_score(self):
return Score.objects.get(exo=self).score
- [Answered ]-Analogs for Placeholder from Django-CMS or Streamfield from Wagtail without cms itself
- [Answered ]-AttributeError: 'module' object has no attribute 'open_openwork'
- [Answered ]-Simple socket call returning socket.gaierror: [Errno 8]