我正在嘗試使用「編輯」按鈕編輯Modelform,但表單未更新。我有一個視圖功能,用於發佈和保存新帖子。然後,我有第二個函數edit_comment
,用於更新原始創建的對象one_entry
。在我的模板中,我有一個提交帖子的表單和一個連接到url「/ edit」的「編輯」按鈕,用URL「/ entry」更新添加的one_entry
對象。任何幫助都很受歡迎。在Django 1.6中編輯表格
# 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中
# 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'中定義了一個表單,然後立即用一個不同的表單替換它? –
現在在視圖 - 部分下添加它,它將視圖功能發佈到模板中並保存表單。我不知道如何以另一種方式使用「實例」。 – user1749431
但是你寫的和'foo =「bar」是一樣的; foo =「baz」 - 第一個變量被定義,然後被替換,而foo等於「baz」。把它定義爲等於「酒吧」是沒有意義的。 –