Skip to main content
In a previous lesson, we encountered an error during post creation. Instead of creating a new post successfully, the application returned a 500 status code. The logs revealed an SQL error indicating that a null value in the “owner_id” column violates the NOT NULL constraint.
The error log was as follows:

Understanding the Issue

The database model defines the owner ID field as non-nullable. Here is a snippet from the model definition:
Despite the model expecting an owner ID, the post creation endpoint did not provide one. The SQL error confirms that when trying to insert a new post, the owner_id field was null. The post schema was purposefully designed to exclude the owner ID from the request body since the authenticated user should be automatically assigned as the owner. Below is the post schema:

Reviewing the API Endpoints

For context, here are the GET and DELETE operations for individual posts:
In the initial POST operation, the owner ID was not set. The code omitted the owner ID, as shown below:
Notice that the PostCreate model does not include the owner ID, as this value must be derived from the currently authenticated user.

The Improved POST Operation

To resolve the issue, update the POST endpoint to automatically assign the owner ID from the authenticated user:
With this change, every new post is automatically linked to the user who is currently authenticated. Testing this change should confirm that the owner ID is stored correctly. For example, executing the following SQL query:
might show that the user with ID 23 (e.g., Sanjeev at Gmail.com) is correctly associated with the new post.

Expected JSON Response

After a successful post creation, the response should look similar to:
The critical change is updating the post creation logic to include:new_post = models.Post(owner_id=current_user.id, **post.dict())This adjustment ensures that each post is automatically linked to its creator.

Watch Video