N
N
Nick V2015-06-02 02:29:59
Django
Nick V, 2015-06-02 02:29:59

How to display comments sorted by date added?

There is a model, a view and a template

model

class Comment(models.Model):

    class Meta:
        db_table = 'comments'

    comment_text = models.TextField(max_length=200, verbose_name='Добавить комментарий')
    comment_created_at = models.DateTimeField(null=True, auto_now=True, verbose_name='Создан')
    comment_product = models.ForeignKey(Product)


views

def product(request, product_slug=None):
    comment_form = CommentForm
    args = {}
    args.update(csrf(request))
    args['product'] = Product.objects.get(product_slug=product_slug)
    args['comments'] = Comment.objects.filter(comment_product_id=product_slug)
    args['username'] = request.user.username
    args['form'] = comment_form
    return render_to_response("product.html", args)


template

{% if comments %}
    <div class="row comment-row">
    {% for comment in comments %}
      <div class="col-md-12">
      <p>{{ comment.comment_created_at|date:"SHORT_DATETIME_FORMAT" }}</p>
      <blockquote class="comment">
      <p>{{ comment.comment_text }}</p>
      </blockquote>
      </div>
    {% endfor %}
    </div>
  {% endif %}


How to make it so that only those comments that appeared in the last 24 hours are displayed, sorted by date added?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Fateev, 2015-06-02
@half-life

In views.py change this line
On those:

date_from = datetime.datetime.now() - datetime.timedelta(days=1)
args['comments'] = Comment.objects.filter(comment_product_id=product_slug, comment_created_at__gte=date_from).order_by('comment_created_at')

And do not forget import datetime
I typed the code immediately in the browser without testing, so there may be errors

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question