Mika
Mika

Reputation: 1162

Django - Validating if user has created an object

I am trying to create a list of high scores. I need to have both high scores all players and high scores of current player. I use django auth.

For some reason I am unable to check whether current user owns the games or not. if current_user.gameshop_user.auth_user == score['user'].user: --> False even if current_user.gameshop_user.auth_user--> Player_one and score['user'].user:--> Player_one.

models.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>
...

Upvotes: 1

Views: 77

Answers (2)

DAKZH
DAKZH

Reputation: 258

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

Here you are comparing contrib.auth.User with models.GameShopUser. Try to compare urrent_user.gameshop_user with score['user'].user

Upvotes: 4

knbk
knbk

Reputation: 53699

You're comparing a GameShopUser object with an auth.User object - those will never be equal.

Use current_user.gameshop_user == score['user'].user instead.

Upvotes: 3

Related Questions