Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

how to fix the date of a DateField as today django

  1. User

    how to fix the date of a DateField as today django

  2. Assistant

    You can set the date of a DateField to today's date in Django by using the auto_now_add attribute in the model.

    Here is an example:

    from django.db import models
    
    class MyModel(models.Model):
        # other fields of the model
        date = models.DateField(auto_now_add=True)
    

    The auto_now_add attribute will automatically set the value of the date field to the current date when the model instance is created for the first time.

    Alternatively, you can update the date field to today's date using the following code when saving the model instance:

    from django.utils import timezone
    
    my_model_instance.date = timezone.now().date()
    my_model_instance.save()
    

    This will set the date field to the current date and save the changes to the database.