Django Validity day counterDoes Django scale?django - inlineformset_factory with more than one ForeignKeyDjango ImageField overwrites existing path when emptydjango models request get id error Room matching query does not existDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerHow to expose some specific fields of model_b based on a field of model_a?How to set dynamic initial values to django modelform fieldHow to define Mode with generic ForeignKey in DjangoDjango: required field even with true=blank on form submisionHow to check if Django Signal works?

What happened to Captain America in Endgame?

Is it idiomatic to construct against `this`

What is the philosophical significance of speech acts/implicature?

A ​Note ​on ​N!

Can an Area of Effect spell cast outside a Prismatic Wall extend inside it?

What term is being referred to with "reflected-sound-of-underground-spirits"?

What does ゆーか mean?

can anyone help me with this awful query plan?

Map of water taps to fill bottles

How do I check if a string is entirely made of the same substring?

How exactly does Hawking radiation decrease the mass of black holes?

How would 10 generations of living underground change the human body?

What happens to Mjolnir (Thor's hammer) at the end of Endgame?

Can someone publish a story that happened to you?

Rivers without rain

Why was the Spitfire's elliptical wing almost uncopied by other aircraft of World War 2?

Minor Revision with suggestion of an alternative proof by reviewer

Don’t seats that recline flat defeat the purpose of having seatbelts?

Why does Mind Blank stop the Feeblemind spell?

How to prevent z-fighting in OpenSCAD?

Aligning equation numbers vertically

Is there any official lore on the Far Realm?

Two field separators (colon and space) in awk

How to denote matrix elements succinctly?



Django Validity day counter


Does Django scale?django - inlineformset_factory with more than one ForeignKeyDjango ImageField overwrites existing path when emptydjango models request get id error Room matching query does not existDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerHow to expose some specific fields of model_b based on a field of model_a?How to set dynamic initial values to django modelform fieldHow to define Mode with generic ForeignKey in DjangoDjango: required field even with true=blank on form submisionHow to check if Django Signal works?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-1















in my app users are able to create posts which have a validity of 100 days. Now i want to display the user how many days are left until his post gets deleted. im currently solving the actual deletion of the post by a celery job which is working greate. My question is only about how to display the number until the validity runs out.
In my opinion i only need a IntegerField with the validity in days and substract it from the creation date.



is there a pratical way to do this?



models.py



class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(verbose_name="Post Title", max_length=40)
content = models.TextField(verbose_name="Post Content", max_length=5000)
tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True)
category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
post_type = models.CharField(default='Free', editable=False, max_length=4)
postattachment = fields.FileField(
verbose_name="Post Attachment",
blank=True,
null=True,
upload_to=get_file_path_user_uploads,
validators=[file_extension_postattachment, file_size_postattachment]
)
postcover = fields.ImageField(
null=True,
blank=True,
upload_to=get_file_path_user_uploads,
validators=[default_image_size, default_image_file_extension],
dependencies=[FileDependency(processor=ImageProcessor(
format='PNG', quality=99, scale='max_width': 700, 'max_height': 700))])
up_vote = models.IntegerField(verbose_name='Post Up-Vote(s)', default=0)
down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0)
published_date = models.DateField(auto_now_add=True, null=True)


thanks and kind regards



UPDATE



models.py



...
down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0)
published_date = models.DateField(auto_now_add=True, null=True)

def days_remaining(published_date):
"""
Returns the remaining days from 'published_date' + 100 days until today.
"""
return published_date + datetime.timedelta(days=100) - datetime.time.today()


template.html



...
<td> post.days_remaining </td>
....









share|improve this question






























    -1















    in my app users are able to create posts which have a validity of 100 days. Now i want to display the user how many days are left until his post gets deleted. im currently solving the actual deletion of the post by a celery job which is working greate. My question is only about how to display the number until the validity runs out.
    In my opinion i only need a IntegerField with the validity in days and substract it from the creation date.



    is there a pratical way to do this?



    models.py



    class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(verbose_name="Post Title", max_length=40)
    content = models.TextField(verbose_name="Post Content", max_length=5000)
    tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True)
    category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
    post_type = models.CharField(default='Free', editable=False, max_length=4)
    postattachment = fields.FileField(
    verbose_name="Post Attachment",
    blank=True,
    null=True,
    upload_to=get_file_path_user_uploads,
    validators=[file_extension_postattachment, file_size_postattachment]
    )
    postcover = fields.ImageField(
    null=True,
    blank=True,
    upload_to=get_file_path_user_uploads,
    validators=[default_image_size, default_image_file_extension],
    dependencies=[FileDependency(processor=ImageProcessor(
    format='PNG', quality=99, scale='max_width': 700, 'max_height': 700))])
    up_vote = models.IntegerField(verbose_name='Post Up-Vote(s)', default=0)
    down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0)
    published_date = models.DateField(auto_now_add=True, null=True)


    thanks and kind regards



    UPDATE



    models.py



    ...
    down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0)
    published_date = models.DateField(auto_now_add=True, null=True)

    def days_remaining(published_date):
    """
    Returns the remaining days from 'published_date' + 100 days until today.
    """
    return published_date + datetime.timedelta(days=100) - datetime.time.today()


    template.html



    ...
    <td> post.days_remaining </td>
    ....









    share|improve this question


























      -1












      -1








      -1


      1






      in my app users are able to create posts which have a validity of 100 days. Now i want to display the user how many days are left until his post gets deleted. im currently solving the actual deletion of the post by a celery job which is working greate. My question is only about how to display the number until the validity runs out.
      In my opinion i only need a IntegerField with the validity in days and substract it from the creation date.



      is there a pratical way to do this?



      models.py



      class Post(models.Model):
      author = models.ForeignKey(User, on_delete=models.CASCADE)
      title = models.CharField(verbose_name="Post Title", max_length=40)
      content = models.TextField(verbose_name="Post Content", max_length=5000)
      tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True)
      category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
      post_type = models.CharField(default='Free', editable=False, max_length=4)
      postattachment = fields.FileField(
      verbose_name="Post Attachment",
      blank=True,
      null=True,
      upload_to=get_file_path_user_uploads,
      validators=[file_extension_postattachment, file_size_postattachment]
      )
      postcover = fields.ImageField(
      null=True,
      blank=True,
      upload_to=get_file_path_user_uploads,
      validators=[default_image_size, default_image_file_extension],
      dependencies=[FileDependency(processor=ImageProcessor(
      format='PNG', quality=99, scale='max_width': 700, 'max_height': 700))])
      up_vote = models.IntegerField(verbose_name='Post Up-Vote(s)', default=0)
      down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0)
      published_date = models.DateField(auto_now_add=True, null=True)


      thanks and kind regards



      UPDATE



      models.py



      ...
      down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0)
      published_date = models.DateField(auto_now_add=True, null=True)

      def days_remaining(published_date):
      """
      Returns the remaining days from 'published_date' + 100 days until today.
      """
      return published_date + datetime.timedelta(days=100) - datetime.time.today()


      template.html



      ...
      <td> post.days_remaining </td>
      ....









      share|improve this question
















      in my app users are able to create posts which have a validity of 100 days. Now i want to display the user how many days are left until his post gets deleted. im currently solving the actual deletion of the post by a celery job which is working greate. My question is only about how to display the number until the validity runs out.
      In my opinion i only need a IntegerField with the validity in days and substract it from the creation date.



      is there a pratical way to do this?



      models.py



      class Post(models.Model):
      author = models.ForeignKey(User, on_delete=models.CASCADE)
      title = models.CharField(verbose_name="Post Title", max_length=40)
      content = models.TextField(verbose_name="Post Content", max_length=5000)
      tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True)
      category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
      post_type = models.CharField(default='Free', editable=False, max_length=4)
      postattachment = fields.FileField(
      verbose_name="Post Attachment",
      blank=True,
      null=True,
      upload_to=get_file_path_user_uploads,
      validators=[file_extension_postattachment, file_size_postattachment]
      )
      postcover = fields.ImageField(
      null=True,
      blank=True,
      upload_to=get_file_path_user_uploads,
      validators=[default_image_size, default_image_file_extension],
      dependencies=[FileDependency(processor=ImageProcessor(
      format='PNG', quality=99, scale='max_width': 700, 'max_height': 700))])
      up_vote = models.IntegerField(verbose_name='Post Up-Vote(s)', default=0)
      down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0)
      published_date = models.DateField(auto_now_add=True, null=True)


      thanks and kind regards



      UPDATE



      models.py



      ...
      down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0)
      published_date = models.DateField(auto_now_add=True, null=True)

      def days_remaining(published_date):
      """
      Returns the remaining days from 'published_date' + 100 days until today.
      """
      return published_date + datetime.timedelta(days=100) - datetime.time.today()


      template.html



      ...
      <td> post.days_remaining </td>
      ....






      python django






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 9 at 9:47







      Venom

















      asked Mar 9 at 9:10









      VenomVenom

      95110




      95110






















          3 Answers
          3






          active

          oldest

          votes


















          0














          You could do something like this:



          models.py



          from django.db import models
          import datetime


          # Create your models here.
          class Post(models.Model):
          author = models.ForeignKey(User, on_delete=models.CASCADE)
          title = models.CharField(verbose_name="Post Title", max_length=40)
          content = models.TextField(verbose_name="Post Content", max_length=5000)
          tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True)
          category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
          post_type = models.CharField(default='Free', editable=False, max_length=4)
          postattachment = fields.FileField(
          verbose_name="Post Attachment",
          blank=True,
          null=True,
          upload_to=get_file_path_user_uploads,
          validators=[file_extension_postattachment, file_size_postattachment]
          )
          postcover = fields.ImageField(
          null=True,
          blank=True,
          upload_to=get_file_path_user_uploads,
          validators=[default_image_size, default_image_file_extension],
          dependencies=[FileDependency(processor=ImageProcessor(
          format='PNG', quality=99, scale='max_width': 700, 'max_height': 700))])
          up_vote = models.IntegerField(verbose_name='Post Up-Vote(s)', default=0)
          down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0)

          published_date = models.DateField(auto_now_add=True, null=True)

          @property
          def remaining_days(self):
          """
          Returns the remaining days defined as: 'published_date' + 100 days - today.
          """
          return (self.published_date + datetime.timedelta(days=100) - datetime.date.today()).days


          views.py



          from django.views import generic
          from .models import Post
          class PostDetailView(generic.DetailView):
          model = Post
          template_name = "post_detail.html"


          post_detail.html



          <!DOCTYPE html>
          <html lang="en">
          <head>
          <meta charset="UTF-8">
          <title>Post Detail</title>
          </head>
          <body>
          <p><strong>Days remaining:</strong> post.remaining_days </p>

          </body>
          </html>



          Screenshot:



          Screenshot






          share|improve this answer
































            0














            Since you have published_date in your model you can find out the number of days it haad been published. For e.g.



            from datetime import datetime

            diff = datetime.now() - published_date



            Now,if max_days = 100 (according to you) then you can simpy do max_days-diff.days will be your expected result.



            I hope this helps you.






            share|improve this answer






























              0














              You can define a method inside your model to calculate that like this:



              class Post(models.Model):
              # ...
              published_date = models.DateTimeField(auto_now_add=True, null=True)

              def get_time_diff(self):
              current_time = datetime.datetime.now()
              delta = current_time-self.published_date
              return delta.days


              use this method in your code or your template:



              post = Post(...)
              if post.get_time_diff > 30:
              # do something


              Update: if you want to calculate remaining days you can add another field in your model (for example days_threshold) that holds an integer of days like this:



              class Post(models.Model):
              # ...
              days_threshold = models.IntegerField(default=100)
              # ...


              In your get_time_diff method you can write something like this:



              def get_time_diff(self):
              current_time = datetime.datetime.now()
              delta = current_time-self.published_date
              remaining_days = self.days_threshold - delta.days
              if remaining_days >= 0
              return remaining_days
              return 0 # for non negative results in day


              Or simply you can add days_threshold hard coded in your method like this:



              def get_time_diff(self):
              current_time = datetime.datetime.now()
              delta = current_time-self.published_date
              remaining_days = 100 - delta.days # I think this is bad practice but works
              if remaining_days >= 0
              return remaining_days
              return 0 # for non negative results in day





              share|improve this answer

























              • Thanks for you quick answere. This seems like what i needed. I simply want to display the left days in a table like: <th style="font-size: small">Validity</th> <td> post.get_time_diff </td> but how can i display it like that: first day: 100 second day: 99 third day: 98 ...

                – Venom
                Mar 9 at 9:34











              • @Venom I update my answer based on what you want

                – shotgunner
                Mar 9 at 10:21











              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55075737%2fdjango-validity-day-counter%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              You could do something like this:



              models.py



              from django.db import models
              import datetime


              # Create your models here.
              class Post(models.Model):
              author = models.ForeignKey(User, on_delete=models.CASCADE)
              title = models.CharField(verbose_name="Post Title", max_length=40)
              content = models.TextField(verbose_name="Post Content", max_length=5000)
              tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True)
              category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
              post_type = models.CharField(default='Free', editable=False, max_length=4)
              postattachment = fields.FileField(
              verbose_name="Post Attachment",
              blank=True,
              null=True,
              upload_to=get_file_path_user_uploads,
              validators=[file_extension_postattachment, file_size_postattachment]
              )
              postcover = fields.ImageField(
              null=True,
              blank=True,
              upload_to=get_file_path_user_uploads,
              validators=[default_image_size, default_image_file_extension],
              dependencies=[FileDependency(processor=ImageProcessor(
              format='PNG', quality=99, scale='max_width': 700, 'max_height': 700))])
              up_vote = models.IntegerField(verbose_name='Post Up-Vote(s)', default=0)
              down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0)

              published_date = models.DateField(auto_now_add=True, null=True)

              @property
              def remaining_days(self):
              """
              Returns the remaining days defined as: 'published_date' + 100 days - today.
              """
              return (self.published_date + datetime.timedelta(days=100) - datetime.date.today()).days


              views.py



              from django.views import generic
              from .models import Post
              class PostDetailView(generic.DetailView):
              model = Post
              template_name = "post_detail.html"


              post_detail.html



              <!DOCTYPE html>
              <html lang="en">
              <head>
              <meta charset="UTF-8">
              <title>Post Detail</title>
              </head>
              <body>
              <p><strong>Days remaining:</strong> post.remaining_days </p>

              </body>
              </html>



              Screenshot:



              Screenshot






              share|improve this answer





























                0














                You could do something like this:



                models.py



                from django.db import models
                import datetime


                # Create your models here.
                class Post(models.Model):
                author = models.ForeignKey(User, on_delete=models.CASCADE)
                title = models.CharField(verbose_name="Post Title", max_length=40)
                content = models.TextField(verbose_name="Post Content", max_length=5000)
                tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True)
                category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
                post_type = models.CharField(default='Free', editable=False, max_length=4)
                postattachment = fields.FileField(
                verbose_name="Post Attachment",
                blank=True,
                null=True,
                upload_to=get_file_path_user_uploads,
                validators=[file_extension_postattachment, file_size_postattachment]
                )
                postcover = fields.ImageField(
                null=True,
                blank=True,
                upload_to=get_file_path_user_uploads,
                validators=[default_image_size, default_image_file_extension],
                dependencies=[FileDependency(processor=ImageProcessor(
                format='PNG', quality=99, scale='max_width': 700, 'max_height': 700))])
                up_vote = models.IntegerField(verbose_name='Post Up-Vote(s)', default=0)
                down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0)

                published_date = models.DateField(auto_now_add=True, null=True)

                @property
                def remaining_days(self):
                """
                Returns the remaining days defined as: 'published_date' + 100 days - today.
                """
                return (self.published_date + datetime.timedelta(days=100) - datetime.date.today()).days


                views.py



                from django.views import generic
                from .models import Post
                class PostDetailView(generic.DetailView):
                model = Post
                template_name = "post_detail.html"


                post_detail.html



                <!DOCTYPE html>
                <html lang="en">
                <head>
                <meta charset="UTF-8">
                <title>Post Detail</title>
                </head>
                <body>
                <p><strong>Days remaining:</strong> post.remaining_days </p>

                </body>
                </html>



                Screenshot:



                Screenshot






                share|improve this answer



























                  0












                  0








                  0







                  You could do something like this:



                  models.py



                  from django.db import models
                  import datetime


                  # Create your models here.
                  class Post(models.Model):
                  author = models.ForeignKey(User, on_delete=models.CASCADE)
                  title = models.CharField(verbose_name="Post Title", max_length=40)
                  content = models.TextField(verbose_name="Post Content", max_length=5000)
                  tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True)
                  category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
                  post_type = models.CharField(default='Free', editable=False, max_length=4)
                  postattachment = fields.FileField(
                  verbose_name="Post Attachment",
                  blank=True,
                  null=True,
                  upload_to=get_file_path_user_uploads,
                  validators=[file_extension_postattachment, file_size_postattachment]
                  )
                  postcover = fields.ImageField(
                  null=True,
                  blank=True,
                  upload_to=get_file_path_user_uploads,
                  validators=[default_image_size, default_image_file_extension],
                  dependencies=[FileDependency(processor=ImageProcessor(
                  format='PNG', quality=99, scale='max_width': 700, 'max_height': 700))])
                  up_vote = models.IntegerField(verbose_name='Post Up-Vote(s)', default=0)
                  down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0)

                  published_date = models.DateField(auto_now_add=True, null=True)

                  @property
                  def remaining_days(self):
                  """
                  Returns the remaining days defined as: 'published_date' + 100 days - today.
                  """
                  return (self.published_date + datetime.timedelta(days=100) - datetime.date.today()).days


                  views.py



                  from django.views import generic
                  from .models import Post
                  class PostDetailView(generic.DetailView):
                  model = Post
                  template_name = "post_detail.html"


                  post_detail.html



                  <!DOCTYPE html>
                  <html lang="en">
                  <head>
                  <meta charset="UTF-8">
                  <title>Post Detail</title>
                  </head>
                  <body>
                  <p><strong>Days remaining:</strong> post.remaining_days </p>

                  </body>
                  </html>



                  Screenshot:



                  Screenshot






                  share|improve this answer















                  You could do something like this:



                  models.py



                  from django.db import models
                  import datetime


                  # Create your models here.
                  class Post(models.Model):
                  author = models.ForeignKey(User, on_delete=models.CASCADE)
                  title = models.CharField(verbose_name="Post Title", max_length=40)
                  content = models.TextField(verbose_name="Post Content", max_length=5000)
                  tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True)
                  category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
                  post_type = models.CharField(default='Free', editable=False, max_length=4)
                  postattachment = fields.FileField(
                  verbose_name="Post Attachment",
                  blank=True,
                  null=True,
                  upload_to=get_file_path_user_uploads,
                  validators=[file_extension_postattachment, file_size_postattachment]
                  )
                  postcover = fields.ImageField(
                  null=True,
                  blank=True,
                  upload_to=get_file_path_user_uploads,
                  validators=[default_image_size, default_image_file_extension],
                  dependencies=[FileDependency(processor=ImageProcessor(
                  format='PNG', quality=99, scale='max_width': 700, 'max_height': 700))])
                  up_vote = models.IntegerField(verbose_name='Post Up-Vote(s)', default=0)
                  down_vote = models.IntegerField(verbose_name='Post Down-Vote(s)', default=0)

                  published_date = models.DateField(auto_now_add=True, null=True)

                  @property
                  def remaining_days(self):
                  """
                  Returns the remaining days defined as: 'published_date' + 100 days - today.
                  """
                  return (self.published_date + datetime.timedelta(days=100) - datetime.date.today()).days


                  views.py



                  from django.views import generic
                  from .models import Post
                  class PostDetailView(generic.DetailView):
                  model = Post
                  template_name = "post_detail.html"


                  post_detail.html



                  <!DOCTYPE html>
                  <html lang="en">
                  <head>
                  <meta charset="UTF-8">
                  <title>Post Detail</title>
                  </head>
                  <body>
                  <p><strong>Days remaining:</strong> post.remaining_days </p>

                  </body>
                  </html>



                  Screenshot:



                  Screenshot







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 9 at 10:07

























                  answered Mar 9 at 9:31









                  Anton BärwaldAnton Bärwald

                  61129




                  61129























                      0














                      Since you have published_date in your model you can find out the number of days it haad been published. For e.g.



                      from datetime import datetime

                      diff = datetime.now() - published_date



                      Now,if max_days = 100 (according to you) then you can simpy do max_days-diff.days will be your expected result.



                      I hope this helps you.






                      share|improve this answer



























                        0














                        Since you have published_date in your model you can find out the number of days it haad been published. For e.g.



                        from datetime import datetime

                        diff = datetime.now() - published_date



                        Now,if max_days = 100 (according to you) then you can simpy do max_days-diff.days will be your expected result.



                        I hope this helps you.






                        share|improve this answer

























                          0












                          0








                          0







                          Since you have published_date in your model you can find out the number of days it haad been published. For e.g.



                          from datetime import datetime

                          diff = datetime.now() - published_date



                          Now,if max_days = 100 (according to you) then you can simpy do max_days-diff.days will be your expected result.



                          I hope this helps you.






                          share|improve this answer













                          Since you have published_date in your model you can find out the number of days it haad been published. For e.g.



                          from datetime import datetime

                          diff = datetime.now() - published_date



                          Now,if max_days = 100 (according to you) then you can simpy do max_days-diff.days will be your expected result.



                          I hope this helps you.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 9 at 9:22









                          Anuj SubediAnuj Subedi

                          3318




                          3318





















                              0














                              You can define a method inside your model to calculate that like this:



                              class Post(models.Model):
                              # ...
                              published_date = models.DateTimeField(auto_now_add=True, null=True)

                              def get_time_diff(self):
                              current_time = datetime.datetime.now()
                              delta = current_time-self.published_date
                              return delta.days


                              use this method in your code or your template:



                              post = Post(...)
                              if post.get_time_diff > 30:
                              # do something


                              Update: if you want to calculate remaining days you can add another field in your model (for example days_threshold) that holds an integer of days like this:



                              class Post(models.Model):
                              # ...
                              days_threshold = models.IntegerField(default=100)
                              # ...


                              In your get_time_diff method you can write something like this:



                              def get_time_diff(self):
                              current_time = datetime.datetime.now()
                              delta = current_time-self.published_date
                              remaining_days = self.days_threshold - delta.days
                              if remaining_days >= 0
                              return remaining_days
                              return 0 # for non negative results in day


                              Or simply you can add days_threshold hard coded in your method like this:



                              def get_time_diff(self):
                              current_time = datetime.datetime.now()
                              delta = current_time-self.published_date
                              remaining_days = 100 - delta.days # I think this is bad practice but works
                              if remaining_days >= 0
                              return remaining_days
                              return 0 # for non negative results in day





                              share|improve this answer

























                              • Thanks for you quick answere. This seems like what i needed. I simply want to display the left days in a table like: <th style="font-size: small">Validity</th> <td> post.get_time_diff </td> but how can i display it like that: first day: 100 second day: 99 third day: 98 ...

                                – Venom
                                Mar 9 at 9:34











                              • @Venom I update my answer based on what you want

                                – shotgunner
                                Mar 9 at 10:21















                              0














                              You can define a method inside your model to calculate that like this:



                              class Post(models.Model):
                              # ...
                              published_date = models.DateTimeField(auto_now_add=True, null=True)

                              def get_time_diff(self):
                              current_time = datetime.datetime.now()
                              delta = current_time-self.published_date
                              return delta.days


                              use this method in your code or your template:



                              post = Post(...)
                              if post.get_time_diff > 30:
                              # do something


                              Update: if you want to calculate remaining days you can add another field in your model (for example days_threshold) that holds an integer of days like this:



                              class Post(models.Model):
                              # ...
                              days_threshold = models.IntegerField(default=100)
                              # ...


                              In your get_time_diff method you can write something like this:



                              def get_time_diff(self):
                              current_time = datetime.datetime.now()
                              delta = current_time-self.published_date
                              remaining_days = self.days_threshold - delta.days
                              if remaining_days >= 0
                              return remaining_days
                              return 0 # for non negative results in day


                              Or simply you can add days_threshold hard coded in your method like this:



                              def get_time_diff(self):
                              current_time = datetime.datetime.now()
                              delta = current_time-self.published_date
                              remaining_days = 100 - delta.days # I think this is bad practice but works
                              if remaining_days >= 0
                              return remaining_days
                              return 0 # for non negative results in day





                              share|improve this answer

























                              • Thanks for you quick answere. This seems like what i needed. I simply want to display the left days in a table like: <th style="font-size: small">Validity</th> <td> post.get_time_diff </td> but how can i display it like that: first day: 100 second day: 99 third day: 98 ...

                                – Venom
                                Mar 9 at 9:34











                              • @Venom I update my answer based on what you want

                                – shotgunner
                                Mar 9 at 10:21













                              0












                              0








                              0







                              You can define a method inside your model to calculate that like this:



                              class Post(models.Model):
                              # ...
                              published_date = models.DateTimeField(auto_now_add=True, null=True)

                              def get_time_diff(self):
                              current_time = datetime.datetime.now()
                              delta = current_time-self.published_date
                              return delta.days


                              use this method in your code or your template:



                              post = Post(...)
                              if post.get_time_diff > 30:
                              # do something


                              Update: if you want to calculate remaining days you can add another field in your model (for example days_threshold) that holds an integer of days like this:



                              class Post(models.Model):
                              # ...
                              days_threshold = models.IntegerField(default=100)
                              # ...


                              In your get_time_diff method you can write something like this:



                              def get_time_diff(self):
                              current_time = datetime.datetime.now()
                              delta = current_time-self.published_date
                              remaining_days = self.days_threshold - delta.days
                              if remaining_days >= 0
                              return remaining_days
                              return 0 # for non negative results in day


                              Or simply you can add days_threshold hard coded in your method like this:



                              def get_time_diff(self):
                              current_time = datetime.datetime.now()
                              delta = current_time-self.published_date
                              remaining_days = 100 - delta.days # I think this is bad practice but works
                              if remaining_days >= 0
                              return remaining_days
                              return 0 # for non negative results in day





                              share|improve this answer















                              You can define a method inside your model to calculate that like this:



                              class Post(models.Model):
                              # ...
                              published_date = models.DateTimeField(auto_now_add=True, null=True)

                              def get_time_diff(self):
                              current_time = datetime.datetime.now()
                              delta = current_time-self.published_date
                              return delta.days


                              use this method in your code or your template:



                              post = Post(...)
                              if post.get_time_diff > 30:
                              # do something


                              Update: if you want to calculate remaining days you can add another field in your model (for example days_threshold) that holds an integer of days like this:



                              class Post(models.Model):
                              # ...
                              days_threshold = models.IntegerField(default=100)
                              # ...


                              In your get_time_diff method you can write something like this:



                              def get_time_diff(self):
                              current_time = datetime.datetime.now()
                              delta = current_time-self.published_date
                              remaining_days = self.days_threshold - delta.days
                              if remaining_days >= 0
                              return remaining_days
                              return 0 # for non negative results in day


                              Or simply you can add days_threshold hard coded in your method like this:



                              def get_time_diff(self):
                              current_time = datetime.datetime.now()
                              delta = current_time-self.published_date
                              remaining_days = 100 - delta.days # I think this is bad practice but works
                              if remaining_days >= 0
                              return remaining_days
                              return 0 # for non negative results in day






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Mar 9 at 10:20

























                              answered Mar 9 at 9:17









                              shotgunnershotgunner

                              1,32421729




                              1,32421729












                              • Thanks for you quick answere. This seems like what i needed. I simply want to display the left days in a table like: <th style="font-size: small">Validity</th> <td> post.get_time_diff </td> but how can i display it like that: first day: 100 second day: 99 third day: 98 ...

                                – Venom
                                Mar 9 at 9:34











                              • @Venom I update my answer based on what you want

                                – shotgunner
                                Mar 9 at 10:21

















                              • Thanks for you quick answere. This seems like what i needed. I simply want to display the left days in a table like: <th style="font-size: small">Validity</th> <td> post.get_time_diff </td> but how can i display it like that: first day: 100 second day: 99 third day: 98 ...

                                – Venom
                                Mar 9 at 9:34











                              • @Venom I update my answer based on what you want

                                – shotgunner
                                Mar 9 at 10:21
















                              Thanks for you quick answere. This seems like what i needed. I simply want to display the left days in a table like: <th style="font-size: small">Validity</th> <td> post.get_time_diff </td> but how can i display it like that: first day: 100 second day: 99 third day: 98 ...

                              – Venom
                              Mar 9 at 9:34





                              Thanks for you quick answere. This seems like what i needed. I simply want to display the left days in a table like: <th style="font-size: small">Validity</th> <td> post.get_time_diff </td> but how can i display it like that: first day: 100 second day: 99 third day: 98 ...

                              – Venom
                              Mar 9 at 9:34













                              @Venom I update my answer based on what you want

                              – shotgunner
                              Mar 9 at 10:21





                              @Venom I update my answer based on what you want

                              – shotgunner
                              Mar 9 at 10:21

















                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55075737%2fdjango-validity-day-counter%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              1928 у кіно

                              Захаров Федір Захарович

                              Ель Греко