0

I'm trying to make a function inside a model that don't return the post published in a future.

This is the model:

from django.db import models
from django.utils import timezone
import datetime


class ModelPost(models.Model):
    title = models.CharField(
        max_length=70,
        unique=True,
        )
    publishing_date = models.DateTimeField(
                        default=timezone.now,
                        )
    contents = models.TextField(
        max_length=200,
        blank=True,
        )

    def __str__(self):
        return self.title

    @property
    def is_future(self):
        if self.publishing_date > datetime.now()
            return True
        return False

The views is this:

def listPostsOnline(request):
    posts_list = BlogPost.objects.all()  #filter(published=True)
    context = {"posts_list": posts_list}
    template = 'blog/reading/list_post_online.html'
    return render(request, template, context)

And this is the template:

{% for p in posts_list %}
  {% if not p.is_future %}
  <div class="container my-4">
    <h3><a href="{{ p.get_absolute_url }}">{{ p.title }}</a></h3>
    <h5>{{ p.publishing_date|date:"d - M - Y | G:i:s" }}</h5>
  </div>
  {% else %}
  <div class="container-full">
    <h1>No data!</h1>
  </div>
  {% endif %}
{% endfor %}

The problem is that I have this error

module 'datetime' has no attribute 'now'

attributed to is_future and I not be able to resolve.

UPDATE

I was inspired by this post

FIRST TRY

I've put from datetime import datetime instead of import datetime and I see this error:

can't compare offset-naive and offset-aware datetimes

SECOND TRY

With import datetime I've put if self.publishing_date > datetime.datetime.now(): instead of if self.publishing_date > datetime.now(): and I see again this:

can't compare offset-naive and offset-aware datetimes

Tom Carrick
  • 6,349
  • 13
  • 54
  • 78
MaxDragonheart
  • 1,117
  • 13
  • 34

1 Answers1

0

The real solution here is to use django.utils.timezone.now() instead of datetime.now()

Tom Carrick
  • 6,349
  • 13
  • 54
  • 78