LoginSignup
2

More than 5 years have passed since last update.

Django2.0でブログの作成(その7:記事の編集)

Posted at

その7

記事の投稿者であれば、その場で編集出来たら良いですよね。
create_articleとdelete_commentの合わせ技です!
投稿者なら編集ボタンを表示させ、編集用htmlに飛ぶという方法をとります。
それでは、let's go!

views.py

記事編集という定義を追加します。

blog/views.py
def edit_article(request, pk):
    article = Post.objects.get(id=pk)

    if request.user.id == article.author.id: #if記事の投稿者
        if request.method == "POST":
            form = forms.PostForm(request.POST, instance=article)
            if form.is_valid():
                article = form.save(commit=False)
                article.author = request.user
                article.save()
            return redirect('blog:article', pk=article.id)
        else:
            form = forms.PostForm(instance=article)
            print(form)
    else: #記事の投稿者でないのならば、記事のページに強制的に戻る
        return redirect('blog:article', pk=article.id)

    return render(request, 'blog/edit_article.html', {
        'article':article, 'form':form
    })

urls.py

追加します。

blog/urls.py
path('article/<int:pk>/edit/', views.edit_article, name='edit_article'),

edit_article.html

記事編集のhtmlを作成します。

edit_article.html
<html>
  <head>
    <!-- bootstrap -->
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
  </head>

  <body>
      <div>
        <a href="{% url 'blog:post_list' %}" class="btn btn-primary">HOMEへ戻る</a>
          <h1><a href="">記事の編集</a></h1><br>

          <form method="post" action="">
            {% csrf_token %}
            {{ form.as_p }}
            <input type="submit">
          </form>

      </div>
  </body>
</html>

commentと同じ感じですね。
何をやっているかわからなくなってしまった方はコチラがオススメ。
DjangoのForm生成が便利すぎる件について

article.html

記事のページに編集ボタンをつけましょう。
もちろん、投稿者にしか編集権限はありませんが、ボタンの表示も記事投稿者のみに制限しておきます。

article.html
{% if request.user.id == article.author.id %}
  <a href="{% url 'blog:edit_article' article.id %}" class="btn btn-primary">記事を編集</a>
{% endif %}

確認

スクリーンショット 2018-10-09 16.55.22.png

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2