【发布时间】:2015-05-29 07:27:50
【问题描述】:
我正在尝试使用“编辑”按钮编辑模型表单,但表单未更新。我有一个视图功能,原始用于发布和保存新帖子。然后我有第二个函数edit_comment,用于更新原始创建的对象one_entry。在我的模板中,我有一个用于提交帖子的表单和一个连接到 url“/edit”的“编辑”按钮,用于更新带有 url“/entry”的表单中添加的 one_entry 对象。非常感谢任何帮助。
在视图中
# function for adding a new post
def original(request, postID):
one_entry = Entry.objects.get(id=postID)
if request.method == 'POST':
form = ReplyForm(request.POST)
if form.is_valid():
postOneComment(request, one_entry)
else:
form = ReplyForm()
c = {"one_entry":one_entry,"form":form,"comment_views":comment_views}
c.update(csrf(request))
return render(request,"template.html", c)
# function for editing/updating the object one_entry
# Comment is a model and content and title are fields in the Modelform
# that should be updated
def edit_comment(request, one_entry):
content = Comment.objects.get(pk=one_entry)
title = Comment.objects.get(pk=one_entry)
if request.method == 'POST':
form = ReplyForm(request.POST, instance=content)
form = ReplyForm(request.POST, instance=title)
if form.is_valid():
postOneComment(request, one_entry)
else:
form = ReplyForm()
c = {"form":form,"one_entry":one_entry}
c.update(csrf(request))
return render(request,"template.html", c)
def postOneComment(request, one_entry):
content = request.POST["content"]
title = request.POST["title"]
user= request.user.username
entryComment = Comment(datetime=datetime.datetime.now(), belongsTo=one_entry,content=content, title=title, user=user)
entryComment.save()
在表格中
class ReplyForm(forms.ModelForm):
title = forms.CharField(max_length=70)
content = forms.CharField(widget=forms.Textarea)
class Meta:
model = Comment
fields = ("title","content", "user")
在网址中
# url for adding a post to object one_entry
url(r'^entry(?P<postID>\d+)$', original),
# url for editing/updating one_entry
url(r'^edit(?P<one_entry>\d+)$',edit_comment),
在模板中
#button for editing one_entry
{% for t in one_entry.comment_set.all %}
<a type="button" href="/edit{{ t.id}}" class="btn btn-xs btn-success">EDIT</button></a>
#form for adding a new post
<form method="post" action="">{% csrf_token %}
<center>Titel (optional){{ form.title}}</center></br>
<center>{{ form.content}}</center>
<center><button type="submit" class="btn btn-success">POST</button></center>
</form>
【问题讨论】:
-
什么是
post_one_comment?还有为什么你在edit_comment中定义一个表单,然后马上换成不同的表单? -
现在将它添加到视图 - 部分下,用于在模板中发布视图 - 功能并保存表单。我不确定如何以另一种方式使用“实例”。
-
但是你写的和
foo = "bar"; foo = "baz"是一样的——第一个变量被定义然后被替换,foo就等于“baz”。首先将其定义为等于“bar”是没有意义的。 -
现在我不明白
postOneComment的意义何在。您已经仔细定义了一个表单并使用实例对其进行了实例化,现在您已经定义了一个完全忽略该表单并直接从 POST 保存评论的单独函数。你为什么要这样做? -
好的,我不知道,如何使用实例变量更新表单字段?
标签: python django forms templates edit