Как проверить вхождение пользователя в таблицу БД?

Добрый день. Суть проблемы в том что имеется страница с обсуждением на которой отображается опрос, не получается сделать проверку на вхождение текущего пользователя в список проголосовавших пользователей.

Models.py (part)
...

class Question(models.Model):
    question_text = models.CharField(max_length=255)
    discussion = models.ForeignKey(Post)
    pub_date = models.DateTimeField(auto_now_add=True)
    voted_users = models.ManyToManyField(CustomUser, default=None, blank=True)

    def get_voted_users(self):
        return "\n".join([u.get_full_name() + "," for u in self.voted_users.all()])

    def __unicode__(self):
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=100)
    votes = models.IntegerField(default=0)

    def __unicode__(self):
        return self.choice_text


view.py
def discussionDetail(request, pk, *args, **kwargs):
    '''Func that show discussion details'''
    post = get_object_or_404(Post, pk=pk)
    form = CommentForm()
    if request.user.is_authenticated():
        if request.method =="POST":
            # Check what form actually send a POST request
            if 'comment_post' in request.POST:
                form = {
                    'comment_body' : request.POST['comment_body'],
                }
                if form['comment_body']:
                    Comment.objects.create(
                        comment_body = form['comment_body'],
                        post = post,
                        user_id = getting_current_user(request),
                    )
                    return redirect('discussion_app:discussion_detail', pk)
                else:
                    messages.add_message(request, messages.INFO, "Comment can't be empty")
                    form = CommentForm()
            elif 'Vote' in request.POST:
                voted = request.POST['choice']
                voted_choice = get_object_or_404(Choice, pk=voted)
                voted_choice.votes += 1
                voted_choice.save()
                voted_question = get_object_or_404(Question, pk=voted_choice.question.id)
                voted_question.voted_users.add(getting_current_user(request))

                messages.add_message(request, messages.INFO, "Voted " + voted )
            else:
                form = CommentForm()

    return render(request, 'discussion_app/discussion_detail.html', {'post':post, 'form':form})


discussion_detail.html (part)
{% if user.is_authenticated %}

    <div id="poll">
        {% for poll in post.question_set.all %}
            {% if user in poll.voted_user.all %}
                <p>You are voted already</p>
            {% else %}
        {{ poll.question_text }}
        <form action="" method="POST">
            {% csrf_token %}
                {% for choice in poll.choice_set.all %}
                <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"/>
                <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br/>
                {% endfor %}
                <input class="btn btn-primary" type="submit" value="Vote" name="Vote" />
        </form>
            {{ poll.voted_users.count }}
            {% endif %}
        {% endfor %}

    </div>

{% endif %}


Собственно я думал что проверка {% if user in poll.voted_user.all %} будет работать, но к сожаление ничего не дает... Подскажите пожалуйста как решить данный вопрос. Если не туда копаю, то хотя бы в какую сторону нужно.
  • Вопрос задан
  • 587 просмотров
Решения вопроса 1
MrLinch
@MrLinch
Just like coding...
Лучше проверку на то что пользователь голосовал делать во view.
Например так:
is_voted = user in question.voted_users.all()
или
is_voted = question.voted_users.filter(pk=user.pk).exists()


И да, так не стоит делать :-)
voted = request.POST['choice']
voted_choice = get_object_or_404(Choice, pk=voted)

Я про то что брать данные прямо из запроса. Лучше используйте формы для этого.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы