如何显示Django表单中的不可编辑字段
问题描述:
我有一个字段为 datetime = models.DateTimeField(auto_now_add = True)
的模型。在根据此模型创建的表单中,我不需要编辑此字段,但需要显示它。不会自动显示具有 auto_now_add = True
的字段。显示此字段的最佳方法是什么?
I've got a model with field datetime = models.DateTimeField(auto_now_add=True)
. In form created from this model I don't need to edit this field but I need to show it. The fields with auto_now_add=True
automatically isn't shown. What is the best way to show this field?
答
假设您通过了实例
创建表单对象时,可以使用以下模板在其中访问它:
Assuming you pass an instance
when creating form object, you can access it in your template using:
{{ form.instance.datetime|date:"Y/m/d H:i:s" }}
如果您没有但是,在一个实例中,最明智的做法是使用当前时间:
If you don't have an instance, though, the smartest thing to do would be to use current time:
{% now "Y/m/d H:i:s" %}