'How can I fix this issue: Provide a one-off default now?
When I run makemigrations I get this error:
You are trying to add the field 'post_date' with 'auto_now_add=True' to user asking without a default; the database needs something
to populate existing rows.
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
Select an option:
In this code I try to set the date field and I find this error. When I do a search about this issue I find that I need to set the default and I set:
from django.utils import timezone
post_date = models.DateField(auto_now_add=True, default=timezone.now())
When I set default I get this error:
WARNINGS:
community.UserAsking.post_date: (fields.W161) Fixed default value provided.
HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If y
ou want to have the current date as default, use `django.utils.timezone.now`
How can I skip this issue and migrate successfully?
models.py:
class UserAsking(models.Model):
userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
title = models.CharField(max_length=100, blank=False, help_text='Be specific and imagine you’re asking a question to another person')
question = models.TextField(max_length=500, blank=False, help_text='Include all the information someone would need to answer your question')
field = models.CharField(max_length=20, choices=CHOICE, default='Technology', help_text='Add the field to describe what your question is about')
post_date = models.DateField(auto_now_add=True)
Solution 1:[1]
The error is saying that since you now want to have a default value for date field, you then need to provide on for the records that are already stored in DB.
First what you need to do is to change this:
models.DateField(auto_now_add=True, default=timezone.now())
to this:
models.DateField(auto_now_add=True)
Next - do as Arakkal Abu adviced:
choose option 1 and type timezone.now and hit enter
Note: you do not need to call method like now() insead just use now (without parentheses)
Solution 2:[2]
Use this instead
DateField(default=django.utils.timezone.now)
This worked for me
Solution 3:[3]
Try: about_title = models.Charfield(max_length, default=“about”)
This worked for me.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Raida |
| Solution 3 | NeverFallingDown 94 |
