I have a simple form that allows a user to create a post. The fields are post_title, post_content, post_date
. The post_title
and post_content
will be provided by the user, however the post_date
will be autogenerated by the system and will give the current timestamp. Due to this, I will only show both title
and content
in the form. When I try and submit a request however, this gives me an IntegrityError saying NOT NULL constraint failed: main_app_post.post_date
. I am fairly new at Django so I really have no idea what to do. I want it that whenever the user sends a Post request (and if it passes the validations), it will generate the current timestamp to post_date
before saving it to the database. Any advices in regards of this? Thanks a lot!
models.py:
class Post(models.Model):
post_title = models.CharField(max_length=100)
post_content = models.TextField(max_length=400)
post_date = models.DateTimeField()
def __str__(self):
return self.post_title
forms.py:
class PostForm(forms.ModelForm):
class Meta:
model = models.Post
fields = ('post_title', 'post_content')
views.py:
if request.method == 'POST':
form = forms.PostForm(request.POST)
if form.is_valid():
post_title = form.cleaned_data['post_title']
post_content = form.cleaned_data['post_content']
post_date = datetime.datetime.now().timestamp()
form.post_date = post_date
form.save(commit=True)