Home > Enterprise >  Django POSTing a TimeStamp to REST API
Django POSTing a TimeStamp to REST API

Time:10-19

When I create and migrate a Model with a DateTimeField I can create an entry in my database which lets me pick the Date I want to log manually. Now I created a Post method to add new entries to my db, but how would I automatically add a Timestamp like the AutoField 'ID' ?

CodePudding user response:

You can use DateTimeField with auto_now_add to your model as the created_at field to log whenever the object is created

https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.DateField.auto_now_add

for example:

class YourModel(models.Model):
    created_at = DateTimeField(auto_now_add=True)
    updated_at = DateTimeField(auto_now=True)

CodePudding user response:

To automatically add value to a object before save it in the database you can override the model save() method or provide the value before save the form in database with form.save(commit=false) :

models.py

class MyModel(models.Model):
    name = models.CharField(default='Empty')
    date = models.DateTimeField(default=datetime.datetime.now, blank=True)
    # Others fields

    # Override model save method
    def save(self, *args, **kwargs):
        # Here you can decide to change the value of a field or add other logic
        self.name = 'Overrided name in save method'
         super(MyModel, self).save(*args, **kwargs)

views.py

def post_view(request):
    if request.method == 'POST':
        form = MyModelForm(request.POST)
        if form.is_valid():
            # Don't save yet because we need to provide the date field
            my_object = form.save(commit=False)
            my_object.date = datetime.datetime.now()
            # Now we can save the object in the database
            my_object.save()
        else:
            # If form is not valid
    else:
        # If request is not POST
  • Related