0

I'm learning about the modelforms helper, and it is my understanding that best practice for form validation will be simply saving the form to a DB model object after simple code like so:

def my_view(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = MyForm(request.POST)
        # check whether it's valid:
        if form.is_valid():

            form.save()

            return redirect somewhere

     else:
        form = MyForm()

return render(request, 'mysite.html', {'form': form})    

However, there is extra data I would like to add to this model object that isn't explicit in the form. For example, what if I wanted to add a date stamp to the object, generated on server side? How do I go about saving more information into the same model object, and what are the best practices for doing so?

DudeDudeDude
  • 329
  • 2
  • 8
  • What do you mean with 'more data'? More fields to a model? – trantu Jun 14 '16 at 21:37
  • Call save with `commit=False`. There are hundreds of examples on SO. – Daniel Roseman Jun 14 '16 at 21:41
  • By more data I mean more fields. Say I have a field in my model that is date time created, but I want to generate that date on server-side, not through the form. How to I add these extra fields to the model object in the DB afterwards? – DudeDudeDude Jun 14 '16 at 21:52
  • Ok, I've found commit-false, thank you Daniel – DudeDudeDude Jun 14 '16 at 22:12
  • Possible duplicate of [Add data to ModelForm object before saving](http://stackoverflow.com/questions/17126983/add-data-to-modelform-object-before-saving) – YPCrumble Jun 15 '16 at 08:33

1 Answers1

0

For trackin creation/modification dates you could use the 'DateTimeField':

created = models.DateTimeField(auto_now_add=True, editable=False)
updated = models.DateTimeField(auto_now=True, editable=False)

auto_now_add inserts the current datetimewhen creating a new object, while auto_now does the same when updating.

For more specific logic you could use the post_save or pre_save signals, or override the save method.

# overriding save
class MyModel(models.Model):
    # ...
    def save(self, *args, **kwargs):
        self.my_field = 'whatever'
        super(MyModel, self).save(*args, **kwargs)   

.

# using signals
from django.db.models.signals import pre_save
from django.dispatch.dispatcher import receiver

@receiver(pre_save, sender=MyModel)
def message_post_save(sender, instance, **kwargs):
    instance.my_field = 'whatever'
ohrstrom
  • 2,890
  • 2
  • 20
  • 34