代码改变世界

126-对已添加文章的编辑,编辑完成后呈现此文章

2020-08-25 11:19  lzhshn  阅读(182)  评论(0编辑  收藏  举报

模板内一篇已经存在的文章,点击编辑后,进入编辑页面,完成编辑后,回到这篇文章的页面(回到原点)。

 

先看文章模板:

        {# show and go to edit a note #}
        <div>
            <h3>{{pk_note.title}}</h3>
            <p><a href="{% url 'notebook:edit_note' pk_note.pk %}">edit</a></p>
            <p>Create time:{{pk_note.pub_time}} Update time:{{pk_note.update_time}}</p>
            {% autoescape off %}
            <p>{{pk_note.content}}</p>
            {% endautoescape %}
            <p>{{pk_note.personal_tags.all}}</p>
        </div>

  

这里会显示文章的各种内容,通过一个edit链接出去,这里除了要指向那个用于编辑的views函数以外,还要传递当前这篇文章的pk值。从文章界面到编辑界面,再重回文章界面,都是对同一个pk值的文章进行操作。

 

在views函数里,需要反向地将一个模型内容,存入到form里,然后显示出来:

def edit_note(request, pk):
    the_note = get_object_or_404(MyNote, id=pk)
    if request.method != 'POST':
        form = NoteForm(instance=the_note)
        all_comment = the_note.comment_set.all().order_by('-add_time')
        context = {'form': form, 'the_note': the_note, 'all_comment': all_comment}
        return render(request, 'edit_note.html', context)
    else:
        form = NoteForm(instance=the_note, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('notebook:one_note', args=[the_note.pk]))

  

关键的表达式是:form = NoteForm(instance=the_note)

由于编辑的模板继承于文章的模板(base.html ——》one_note.html ——》edit_note.html),而文章模板里有显示已经存在的评论,因此这里还需要取出所有的评论,并且放入上下文。

if的部分,负责呈现编辑界面,else的部分负责保存编辑的内容,以及跳转,else的部分和新增一篇文章基本上完全一致。

 

        {% block content %}
        {# edit a note and show again #}
        <div class="left">
            <form action="{% url 'notebook:edit_note' the_note.pk %}" method="post">
                {% csrf_token %}
                {{form.as_p}}
                <input type="submit" value="Save" />
            </form>

        </div>
        {% endblock content %}

  

编辑的模板就是将前面提到的form里的内容呈现出来,在提交后,重新回到edit_note函数。

这里要特别注意,这个模板在提交后需要回传当前文章的pk值,因此,还要把代表这个文章的变量也传入到上下文:'the_note': the_note,然后在action里,把pk值取出来。