Menu
CoddyTech

LoginRequiredMixin

CoddyのDjangoジャーニー「クラスベースビュー」セクションの一部。レッスン 14/18。

現時点では、アカウントがなくても誰でも求人を投稿、編集、削除できます。クラスには@login_requiredを付けるための単一の関数がないため、Djangoではミックスインを使います。これは、追加の動作を1つ加えるためにビューの親クラスに追加する小さなクラスです。

from django.contrib.auth.mixins import LoginRequiredMixin


class RecipeCreateView(LoginRequiredMixin, CreateView):
    model = Recipe
    fields = ["title", "minutes"]

ログアウト中の訪問者は、ビューが実行される前に、GETとPOSTのどちらでも/accounts/login/?next=/recipes/new/にリダイレクトされます。ログインすると、nextによって元のページに戻ります。

ミックスインは最初に置きます。すべてのビューはdispatch()というメソッドから始まり、Pythonは左から右の順に親クラスを調べます。(CreateView, LoginRequiredMixin)と書くと、ビュー自身のdispatch()が優先され、ログインチェックは実行されず、何の警告も表示されません。

challenge icon

チャレンジ

中級

ログイン済みのユーザーのみ、求人の投稿、編集、削除ができます。

  • JobCreateView、JobUpdateView、JobDeleteViewにLoginRequiredMixinを追加します。
  • 求人一覧と求人ページは、誰でも引き続き閲覧できます。

「Run」を押してからPost a jobを押すと、ログインページに移動します。adaとしてログインします。パスワードはcoddy-pass-123です。

自分で試してみよう

from django.urls import reverse_lazy
from django.views.generic import CreateView, DeleteView, DetailView, ListView, TemplateView, UpdateView

from .models import Job


class HomeView(TemplateView):
    template_name = "jobs/home.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["count"] = Job.objects.count()
        context["latest"] = Job.objects.order_by("-posted").first()
        return context


class AboutView(TemplateView):
    template_name = "jobs/about.html"


class JobListView(ListView):
    model = Job
    context_object_name = "jobs"
    ordering = ["-posted"]
    paginate_by = 5

    def get_queryset(self):
        jobs = super().get_queryset()
        city = self.request.GET.get("city")
        if city:
            jobs = jobs.filter(city=city)
        return jobs


class JobDetailView(DetailView):
    model = Job


class JobCreateView(CreateView):
    model = Job
    fields = ["title", "company", "city", "salary", "description"]


class JobUpdateView(UpdateView):
    model = Job
    fields = ["title", "company", "city", "salary", "description"]


class JobDeleteView(DeleteView):
    model = Job
    success_url = reverse_lazy("jobs:list")

クラスベースビューのすべてのレッスン

自分で練習してみよう: Djangoプレイグラウンド