2

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

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

编辑帖子.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 %}
4

1 回答 1

0

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

def save(self, *args, **kwargs):
    self.timestamp = datetime.now()
    super(Dog,self).save(*args, **kwargs)
于 2013-06-14T16:05:39.057 回答