更新日期时间字段(来自系统),但不要让用户看到它

时间:2013-01-14 22:40:11

标签: django-forms

以下是我的“视图”,它通过“editpost.html”呈现表单。我想更新系统时间要编辑的时间戳(日期时间字段),但不希望用户看到它。我尝试在modelform定义Meta类中使用“hidden”关键字,但这并没有正确更新时间。我尝试在模板中执行此操作但不起作用。有什么想法吗?

def editpost(request, postid):    
    blog = BlogPost.objects.get(pk=postid)
    if request.method == 'POST':
        form = BlogPostForm(request.POST, instance=blog)
        blog = form.save()
        return HttpResponseRedirect('/blog/%s' % str(postid))
    else:
        form = BlogPostForm(initial={'timestamp': datetime.now()}, instance=blog)
        form.save(commit=False)
    return render_to_response("editpost.html", {'form': form, 'postid': postid}, RequestContext(request))

editpost.html

{% block content %}
<form action="." method="post">{% csrf_token %}
    {% for field in form %}
        {% if field.label_tag != "Timestamp" %}
            <div class="fieldWrapper">
                {{ field.errors }}
                {{ field.label_tag }} {{ field }}
            </div>
        {% endif %}
    {% endfor %}
<input type="submit" value="Save" />
</form>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

可能更好的是重写模型的def save(...)。你可以尝试一下:

def save(self, *args, **kwargs):
    self.timestamp = datetime.now()
    super(Dog,self).save(*args, **kwargs)