After resetting uwsgi, the default=datetime.now() in Django models consistently saves the exact same datetime

I encountered an issue with my model code that involved datetime settings:

added_time = models.DateTimeField(
    default=datetime.datetime.now()
)

Upon migrating and restarting uwsgi, I noticed that the first datetime entry in MariaDB was correct, but all subsequent entries were identical to the initial one after resetting uwsgi.

2015-04-19 16:01:46
2015-04-19 16:01:46
2015-04-19 16:01:46
2015-04-19 16:01:46

To address this issue, I made a change to the code as follows:

added_time = models.DateTimeField(
    auto_now_add=True
)

Although this adjustment resolved the problem, I'm still unsure of why this behavior occurred in the first place.

Answer №1

default=datetime.datetime.now() is calculated when the model is parsed/compiled and remains unchanged afterwards. To calculate now() at the time of adding/updating an object, you should use:

default=datetime.datetime.now, which assigns now as a callable function. Django will execute it during runtime.

Using auto_now_add is also a valid solution (though subtly different -- providing a default value will update it each time the model is saved, while auto_now_add only does it once, upon creation).

Do not worry, this error is a very common oversight.

Answer №2

Make sure to pass in datetime.datetime.now instead of datetime.datetime.now() as the default value. This way, the default value is calculated only when needed and not always on model initialization, ensuring you get a different value after each restart.

For a more detailed explanation, refer to the Django documentation.

If you are using Django's time zones support, be sure to utilize django.utils.timezone.now instead of datetime.datetime.now.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generate a line graph that displays distinct colors for each row group and varying line styles for columns

I am working with the dataframe df provided below. How can I modify it so that each run is represented by a different color on its own line? Additionally, I want the values from column "Val_B" to be displayed as dashed lines, and the values from column "Va ...

Are mistake entries in a DataFrame using .loc in Pandas a bug or a misunderstanding?

Is there a way to update the contents of an excel file using values from a Python dictionary? I've been trying to use the .loc function, but it seems to be working inconsistently. Sometimes it writes the correct values, and other times it writes the c ...

Utilizing Python's regular expressions for parsing and manipulating Wikipedia text

I am attempting to convert wikitext into plain text using Python regular expressions substitution. There are two specific formatting rules for wiki links: [[Name of page]] [[Name of page | Text to display]] (http://en.wikipedia.org/wiki/Wikipedia:Cheat ...

Python and Selenium - Dealing with Authentication Pop-Up without the use of URL username and password parameters

Is there a way to authenticate without exposing parameters in the URL? The solution requires manually handling alerts (switching to alert, authenticating, then switching back to the original window) using Selenium's Alert Class method. Below is the f ...

What is the best way to transmit data through a web socket connection effectively?

When it comes to sending data over a web socket connection, is there an optimal method? In my specific scenario, I am transmitting data from a C# application to a Python (Tornado) web server by sending a string with multiple elements separated by commas. I ...

Using Python and Selenium to trigger a 2FA email on the Palo Alto website

I'm currently working on a script to download a file from the Palo Alto Networks website. Everything is going smoothly so far - I've managed to input the username and password successfully. However, I'm encountering an issue when it comes to ...

Transforming DBF documents into CSV style utilizing ydbf

I've been working on converting a specific DBF file into CSV format, and I'm encountering an issue with one particular value in the script. My tool of choice for this task is the ydbf package in Python. So far, I have a total of 598 DBF files th ...

The REST API in Python encountered an error when attempting to cast a JSONArray to a JSONObject

I'm working on a python script that has two main tasks: Parse a CSV file Send the parsed data to a remote server using its REST API So far, my code successfully parses the CSV file and converts it into a JSON object. However, when I try to send th ...

Python Script Running in Docker Encounters Errors with Missing Files, Failing to Execute

For the past year, I've been successfully running a python script within a Docker environment without any major issues. However, after updating to Docker version 4.25.0 about a month ago, my python script stopped working properly. I managed to fix s ...

Utilizing PyCharm with Python, one can seamlessly navigate between frames using the driver.switch_to.default_content() method

After executing the code snippet below, I encountered a syntax error that has left me perplexed: import pytest from selenium import webdriver @pytest.fixture(scope="class") def setup(request): global driver browser_name=request.config.g ...

Transmit two arguments to the Celery task with an estimated time of arrival

When using eta to schedule a task: test.apply_async(eta=datetime(2019, 8, 4, 17, 01)) I have a task in test.py that requires an argument from the view, such as 'post': app = Celery() @app.task(bind=True) def test(post, self): #somecode I ...

Unable to retrieve information from the JSON object

Here's the script I'm working with: <script type="text/javascript> function getData(username){ $.ajax({ url: '{% url "data" %}', data: { ' ...

The system encountered an error in converting the string to float: 'Sneezing'

import pandas as pd from sklearn.tree import DecisionTreeClassifier Health_data = pd.read_csv("Health_dataset.csv") X = Health_data.drop(columns='Conditions') y = Health_data['Conditions'] model = DecisionTreeClassifier() ...

Utilizing Python to manipulate the 'select' tag in HTML

Currently, I am attempting to retrieve events from an HTML page located at In my efforts to choose different areas using python script, I encountered a challenge with the following snippet of HTML code: <select data-ng-options="key as value.name for ( ...

Error encountered while attempting a simple input operation

Hey there! So, I'm pretty new to python and I have a question about a simple script I'm working on: print('What is your name?') person = input("Enter name: ") print("Hello ", person) But every time I run it, I get this error message: ...

What is the best way to create a plot of a two-dimensional random walk using Python?

Recently, I developed a code for a two-dimensional random walk: def r2walk(T): x = np.zeros((T)) y = np.zeros((T)) x = [0]*T y = [0]*T for t in range(0,T): walk = random.random() if 0 < walk < .25: x[t ...

Execute the func(df) command to generate fresh data sets and assign new names to them

After executing func(df), is it possible to maintain the original names of df10 & df20 and access them individually, or even change their names? df = pd.DataFrame( { 'A': ['d','d','d','d','d', ...

I encountered a malfunction in a section of Python 3 code that I created

Unfortunately, the code snippet below is experiencing some issues. Error: '<' not supported between instances of 'str' and 'int' Code: name = input() age = input() if name == ('alice'): print('hello alice ...

What is the best way to ensure that your regular expression returns all capture groups?

Looking to extract specific values from a string that follows the pattern RAM 1000/2000/3000/4000. Using regular expressions, how can I extract RAM 1000, 2000, 3000, and 4000? I've tried using (RAM 1000)(?:(?:\/)(\w+)){1,}, but it only capt ...

Searching for an HTML element within another using selenium

Is there a way to use the list of elements I obtained with find_elements method in a for loop to search for elements containing a specific string and ensure they each contain a span with certain text? today = self.dataBrowser.find_elements(By.XPATH, f&apos ...