Método de votación Ascendente/Descendente de Django [cerrado]


Estoy haciendo una pequeña aplicación que permite a los usuarios votar elementos ya sea hacia arriba o hacia abajo. Estoy usando Django (y nuevo en él!).

Me pregunto cuál es la mejor manera de presentar el enlace de upvote al usuario. Como un enlace, botón o algo más?

Ya he hecho algo como esto en php con un framework diferente pero no estoy seguro si puedo hacerlo de la misma manera. Debo tener un método para votar arriba/abajo y luego mostrar un enlace al usuario para hacer clic. Cuando hacen clic en él, realiza la método y actualiza la página?

Author: irl_irl, 2009-10-07

4 answers

Solo plug and play:

RedditStyleVoting
Implementando la votación estilo reddit para cualquier Modelo con django-voting
http://code.google.com/p/django-voting/wiki/RedditStyleVoting

 12
Author: panchicore,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-25 00:20:18

Aquí está la esencia de mi solución. Uso imágenes con jQuery / AJAX para manejar clics. Fuertemente influenciado por este sitio. Hay algunas cosas que podrían necesitar un poco de trabajo (manejo de errores en el cliente, por ejemplo -- y gran parte de él probablemente podría ser refactorizado) pero esperemos que el código es útil para usted.

El HTML:

        <div class="vote-buttons">
        {% ifequal thisUserUpVote 0 %}
        <img class="vote-up" src = "images/vote-up-off.png" title="Vote this thread UP. (click again to undo)" />
        {% else %}
        <img class="vote-up selected" src = "images/vote-up-on.png" title="Vote this thread UP. (click again to undo)" />
        {% endifequal %}
        {% ifequal thisUserDownVote 0 %}
        <img class="vote-down" src = "images/vote-down-off.png" title="Vote this thread DOWN if it is innapropriate or incorrect. (click again to undo)" />
        {% else %}
        <img class="vote-down selected" src = "images/vote-down-on.png" title="Vote this thread DOWN if it is innapropriate or incorrect. (click again to undo)" />
        {% endifequal %}
        </div> <!-- .votebuttons -->

El jQuery:

$(document).ready(function() {

    $('div.vote-buttons img.vote-up').click(function() {

        var id = {{ thread.id }};
        var vote_type = 'up';

        if ($(this).hasClass('selected')) {
            var vote_action = 'recall-vote'
            $.post('/ajax/thread/vote', {id:id, type:vote_type, action:vote_action}, function(response) {
                if (isInt(response)) {
                    $('img.vote-up').removeAttr('src')
                        .attr('src', 'images/vote-up-off.png')
                        .removeClass('selected');
                    $('div.vote-tally span.num').html(response);
                }
            });
        } else {

            var vote_action = 'vote'
            $.post('/ajax/thread/vote', {id:id, type:vote_type, action:vote_action}, function(response) {
                if (isInt(response)) {
                    $('img.vote-up').removeAttr('src')
                        .attr('src', 'images/vote-up-on.png')
                        .addClass('selected');
                    $('div.vote-tally span.num').html(response);
                }
            });
        }
    });

La vista Django que maneja la solicitud AJAX:

def vote(request):
   thread_id = int(request.POST.get('id'))
   vote_type = request.POST.get('type')
   vote_action = request.POST.get('action')

   thread = get_object_or_404(Thread, pk=thread_id)

   thisUserUpVote = thread.userUpVotes.filter(id = request.user.id).count()
   thisUserDownVote = thread.userDownVotes.filter(id = request.user.id).count()

   if (vote_action == 'vote'):
      if (thisUserUpVote == 0) and (thisUserDownVote == 0):
         if (vote_type == 'up'):
            thread.userUpVotes.add(request.user)
         elif (vote_type == 'down'):
            thread.userDownVotes.add(request.user)
         else:
            return HttpResponse('error-unknown vote type')
      else:
         return HttpResponse('error - already voted', thisUserUpVote, thisUserDownVote)
   elif (vote_action == 'recall-vote'):
      if (vote_type == 'up') and (thisUserUpVote == 1):
         thread.userUpVotes.remove(request.user)
      elif (vote_type == 'down') and (thisUserDownVote ==1):
         thread.userDownVotes.remove(request.user)
      else:
         return HttpResponse('error - unknown vote type or no vote to recall')
   else:
      return HttpResponse('error - bad action')


   num_votes = thread.userUpVotes.count() - thread.userDownVotes.count()

   return HttpResponse(num_votes)

Y las partes relevantes del modelo de hilo:

class Thread(models.Model):
    # ...
    userUpVotes = models.ManyToManyField(User, blank=True, related_name='threadUpVotes')
    userDownVotes = models.ManyToManyField(User, blank=True, related_name='threadDownVotes')
 31
Author: Matt Miller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-07 04:55:55

Haga lo que haga, asegúrese de que se envía por CORREO y no por GET; Las solicitudes GET deben nunca alterar la información de la base de datos.

 10
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-06 23:18:43

Como un enlace, botón o algo más?

Otra cosa, ¿qué pasa con una imagen?

Cuando hacen clic en él, realiza el método y actualiza la página?

Quizás podría usar mejor ajax para invocar un método para guardar el voto, y no actualizar nada en absoluto.

Esto es lo que me viene a la mente.

introduzca la descripción de la imagen aquí

 6
Author: OscarRyz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-22 00:45:33