我正在尝试选择selected
中的选项。在我的代码中,每个用户都给彼此分数。我尝试过一些东西,但它不起作用。如果所选值等于给予用户的等级,则该选项应保持选中状态。我使用AbstractUser
这就是User = get_user_model()
的原因,但我决定不显示它,因为它没用。
models.py
class Score(models.Model):
VALUE = (
(1, "Score 1"),
(2, "Score 2"),
(3, "Score 3"),
(4, "Score 4"),
(5, "Score 5"),
(6, "Score 6"),
(7, "Score 7"),
(8, "Score 8"),
(9, "Score 9"),
(10, "Score 10"),
)
granted_by = models.ForeignKey(settings.AUTH_USER_MODEL, default=0)
granted_to = models.ForeignKey(settings.AUTH_USER_MODEL, default=0, related_name='granted_to')
grade = models.PositiveSmallIntegerField(default=0, choices=VALUE)
def __str__(self):
return str(self.granted_to)
views.py
@login_required(login_url='/login/')
def vote(request):
User = get_user_model()
data = dict()
data['users'] = User.objects.exclude(username=request.user)
if request.method == "POST":
if "rating" in request.POST:
for key in request.POST:
if 'grade_' in key:
awarded_grade = Score.objects.filter(granted_by=request.user,
granted_to__id=key.split('_')[1]).first()
if awarded_grade:
awarded_grade.grade = request.POST.get(key)
awarded_grade.save()
else:
Score.objects.create(granted_by=request.user,
granted_to_id=key.split('_')[1],
grade=request.POST.get(key))
data['values'] = Score.VALUE
data['grade'] = Score.objects.filter(granted_by=request.user)
return render(request, 'vote.html', data)
vote.html
{% for user in users %}
<tr>
<td>{{ user.date_joined|date:"d.m.Y H:i" }}</td>
<td>{{ user.username }} </td>
<td>{{ user.id }}</td>
<td>
<select title="selecting_grade" name="grade_{{ user.id }}">
{% for value in values %}
<option value="{{ value.0 }}" {% for a in grades %} {% if a.grade == value.0 %}selected{% endif %} {% endfor %} >{{ value.0 }}</option>
{% endfor %}
</select>
</td>
</tr>
{% endfor %}
我在控制台中试过这样的东西:
user_grade = Score.objects.filter(granted_by__username='Stalone', granted_to__username='Fane')
user_grade
<QuerySet [<Score: Fane>]>
for x in granted_user:
print(x.grade)
2
或:
a = CustomUser.objects.all()
for user in a:
grades = user.granted_to.values()
print(grades)
<QuerySet [{'id': 22, 'grade': 5, 'granted_to_id': 14, 'granted_by_id': 1}]>
<QuerySet [{'id': 21, 'grade': 5, 'granted_to_id': 15, 'granted_by_id': 1}]>
<QuerySet [{'id': 19, 'grade': 5, 'granted_to_id': 16, 'granted_by_id': 1}]>
<QuerySet [{'id': 23, 'grade': 7, 'granted_to_id': 17, 'granted_by_id': 1}]>
<QuerySet [{'id': 20, 'grade': 8, 'granted_to_id': 18, 'granted_by_id': 1}]>
<QuerySet [{'id': 24, 'grade': 7, 'granted_to_id': 19, 'granted_by_id': 1}]>
为了看看我是否可以获得给每个用户的分数并在选中使用它们,我得到了它们,但我没有设法使用它们,有什么建议吗?
答案 0 :(得分:1)
在views.py中,您传递了grade
data['grade'] = Score.objects.filter(granted_by=request.user)
但是在vote.html中,您正在使用grades
<option value="{{ value.0 }}" {% for a in grades %} {% if a.grade == value.0 %}selected{% endif %} {% endfor %} >{{ value.0 }}</option>
将grade
更改为grades
中的views.py
或将grades
更改为grade
中的vote.html