K
K
Kirill Pisarev2015-08-04 00:17:48
Django
Kirill Pisarev, 2015-08-04 00:17:48

How to check if a user is in a database table?

Good afternoon. The essence of the problem is that there is a page with a discussion on which the poll is displayed, it is not possible to check whether the current user is in the list of voted users.
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 %}

Actually, I thought that the {% if user in poll.voted_user.all %} check would work, but unfortunately it does not give anything ... Please tell me how to solve this issue. If I’m not digging there, then at least in which direction I need to.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Savchuk, 2015-08-04
@P1sar

It's better to check what the user voted to do in the view.
For example like this:
or
And yes, you shouldn't do that :-)

voted = request.POST['choice']
voted_choice = get_object_or_404(Choice, pk=voted)

I about that that to take the data directly from request. Better use forms for this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question