python - Django - 验证用户是否创建了一个对象

标签 python django

我正在尝试创建一个高分列表。我需要同时拥有所有玩家的高分和当前玩家的高分。我使用 django 身份验证。

出于某种原因,我无法检查当前用户是否拥有游戏。 if current_user.gameshop_user.auth_user == score['user'].user: --> False 即使 current_user.gameshop_user.auth_user--> Player_one 和 score['user'].user:--> Player_one.

模型.py

...
class GameShopUser(models.Model):
  auth_user = models.OneToOneField(User, related_name='gameshop_user')
  email_validated = models.BooleanField(default=False)

class ScoreEntry(models.Model):
  timestamp = models.DateTimeField('date scored')
  score = models.IntegerField()
  user = models.ForeignKey('GameShopUser', related_name='scores')
  game = models.ForeignKey('Game', related_name='scores')

view.py

...
def play_view(request, slug):

  current_user = request.user
    queryset = ScoreEntry.objects.order_by('-score')
    high_scores = queryset[:3]
    all_scores_without_index = queryset.values()

    all_scores = []
    i = 0

    for score in all_scores_without_index:
      i += 1
      all_scores.append(score)
      score['index'] = i
      score['user'] = ScoreEntry.objects.get(id=score['id'])

    high_scores_of_current_player = []
    for score in all_scores:
      if current_user.gameshop_user.auth_user == score['user'].user:
        print("success")

    print(current_user)
    print(score['user'].user)

    top = {}
    top_score = 0
    for score in all_scores:
        if score['score'] > top_score:
          top_score = score['score']
          top = score
...

play.html

...
  <h4>High Scores</h4>
  <table class="table">
    {% for scoreEntry in high_scores %}
      <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ scoreEntry.user }}</td>
        <td>{{ scoreEntry.score }}</td>
      </tr>
    {% endfor %}
  </table>
<h4>My High Scores</h4>
  <table class="table">
        <tr>
          <td>{{ top.index }}</td>
          <td>{{ top.user.user }}</td>
          <td>{{ top.score }}</td>
        </tr>
  </table>
</div>
...

最佳答案

current_user.gameshop_user.auth_user == score['user'].user

此处您将 ​​contrib.auth.User 与 models.GameShopUser 进行比较。尝试将 urrent_user.gameshop_user 与 score['user'].user 进行比较

关于python - Django - 验证用户是否创建了一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27746078/

相关文章:

python - 来自原始 SQL 插入的 sqlalchemy PK

python - 提交空表格和奇怪的输出

python - Django:使用 <select multiple> 和 POST

bool 值的 Django 过滤器

python - 火星 2020 网页抓取

python - 将 json 对象列表展平到表中,并为 Databricks 中的每个对象提供列

python - 给定一个值,使用 Numpy 查找百分位数 %

python - 是否可以使用 FB Prophet 进行多元多步预测?

python - 在 Django 中为详细信息 View 创建页面访问者计数

Django:如何获取当前 URL 标记名(用于分页)?