0

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)
Dran Dev
  • 529
  • 3
  • 20

2 Answers2

1

set auto_now_add=True

class Post(models.Model):
    post_title = models.CharField(max_length=100)
    post_content = models.TextField(max_length=400)
    post_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.post_title

Refernce: Django auto_now and auto_now_add

JPG
  • 82,442
  • 19
  • 127
  • 206
1

You can specify a default and make it non-editable, but in fact Django already has a solution for this: you can specify auto_now_add=True [Django-doc]:

class Post(models.Model):
    post_title = models.CharField(max_length=100)
    post_content = models.TextField(max_length=400)
    post_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.post_title

This will make the field non-editable, so it will not show up in a form by default, and furthermore it will use as default value the current timestamp. This thus means that the view and form no longer have to worry about this.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555