M
M
MalikDeveloper20772020-02-26 15:16:20
Django
MalikDeveloper2077, 2020-02-26 15:16:20

Can't access a field in a model in a Django template?

I need to check if the user is in the list of those who bookmarked the quiz, then display one, otherwise - the other.
Here is the bookmark model:

class Bookmark(models.Model):
    """Bookmar for a quiz"""
    quiz = models.ForeignKey(
        Quiz,
        on_delete=models.PROTECT,
        verbose_name='Викторина',
        related_name='bookmarks'
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        verbose_name='Пользователь',
        related_name='bookmarks'
    )


I have such a template and the question is how to check the user for bookmarks to this quiz
<span class="quiz__bookmarks ml-3">
            {% if user in quiz.get_bookmarks_users %}
              <i class="fas fa-star bookmarked-star"></i>
            {% else %}
              <i class="far fa-star"></i>
            {% endif %}
            {{ quiz.get_bookmarks_count }}
</span>


Therefore, I tried to make a method in the model to get all users who bookmarked this quiz
def get_bookmarks_users(self):
        return self.bookmarks.all().user


But I'm doing something wrong, tell me how to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wondermarin, 2020-02-26
@MalikDeveloper2077

One option:
views.py:

...
bookmarks = Bookmark.all()
context['bookmarks'] = bookmarks
...

your template:
<span class="quiz__bookmarks ml-3">
            {% for bookmark in bookmarks %}
                {% if user in bookmark.user %}
                  <i class="fas fa-star bookmarked-star"></i>
                {% else %}
                  <i class="far fa-star"></i>
                {% endif %}
            {% endfor %}
            {{ quiz.get_bookmarks_count }}
</span>

Well, or you can check it in views.py.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question