将Django表单保存到DB

时间:2016-06-14 21:22:01

标签: django

我正在学习modelforms帮助器,我的理解是,表单验证的最佳实践只是在简单代码之后将表单保存到DB模型对象中:

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})    

但是,我希望添加到此模型对象中的额外数据在表单中不明确。例如,如果我想在服务器端生成的对象上添加日期戳,该怎么办?如何将更多信息保存到同一模型对象中,以及这样做的最佳实践是什么?

1 个答案:

答案 0 :(得分:0)

对于trackin创建/修改日期,您可以使用'DateTimeField':

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

auto_now_add在创建新对象时插入当前datetime,而auto_now在更新时也会这样做。

对于更具体的逻辑,您可以使用post_savepre_save信号,或覆盖save方法。

# 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'