2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

DjangoでMixinを使って、自分のプロフィールのみ編集できるようにする

Last updated at Posted at 2020-11-21

概要

  • プロフィール編集画面のViewを作成する際に、自分のプロフィールのみアクセス可能とするMixinクラスベース汎用ビュー を継承したクラスを作成する

Mixinとは

  • あるクラスと直接は関連しない処理をまとめたもの
  • 多重継承で、他のクラスに機能を追加できる

django.contrib.auth.mixins を使う

実装(各ファイルの変更)

urls.py への追加

    path('detail/<int:pk>/', UserDetailView.as_view(), name='member_detail'),
    path('update/<int:pk>/', UserUpdateView.as_view(), name='member_update'),

views.py への追加

  • (ユーザ種別ごとに入力項目を変えたいので、Form関連の記述は別途記載予定)

from django.contrib.auth.mixins import UserPassesTestMixin
from django.views.generic import DetailView, UpdateView


class OnlyYouMixin(UserPassesTestMixin):
    raise_exception = False     # set True if raise 403_Forbidden

    def test_func(self):
        user = self.request.user
        return user.pk == self.kwargs['pk'] or user.is_superuser


class UserDetailView(OnlyYouMixin, DetailView):
    model = CustomUser
    template_name = 'account/detail.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        pass  # 必要に応じて処理を追加
        return context


class UserUpdateView(OnlyYouMixin, UpdateView):
    model = CustomUser
    template_name = 'account/update.html'

    def get_success_url(self):
        return resolve_url('member_detail', pk=self.kwargs['pk'])

テンプレートの追加

  • 上記のviews.pyで指定した位置にテンプレートを配置
  • ヘッダー部に、プロフィール表示へのリンクを表示

            <li class="nav-item"><a class="nav-link" href="{% url 'member_detail' user.pk %}">Show Profile</a></li>

参考

参考その2

2
2
0

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?