Menu
CoddyTech

UpdateView

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

求人を投稿した人は、自分の求人を修正する必要があります。行を編集するのは新しい行を作成するのと似ていますが、フォームには最初から値が入力されており、保存すると新しい行が追加されるのではなく、既存の行が変更されます。UpdateViewはその両方を行います。レシピサイトの場合:

class RecipeUpdateView(UpdateView):
    model = Recipe
    fields = ["title", "cuisine", "minutes"]


# urls.py
path("recipes/<int:pk>/change/", views.RecipeUpdateView.as_view(), name="change")

DetailViewと同じ方法で、URL内のpkまたはslugを使って行を見つけ、該当する行がない場合は404を返します。保存後はCreateViewと同じ遷移先に進みます。success_url、またはその行のget_absolute_url()です。

CreateViewとrecipes/recipe_form.htmlを共有し、その行をobjectとして追加するため、編集中の場合にのみ{% if object %}が真になります。fieldsは必須です。Djangoが、訪問者が変更できるフィールドを推測することはありません。

challenge icon

チャレンジ

簡単

求人ページにEditリンクが追加されました。そのリンク先のページを作成してください。

  • JobUpdateViewを作成します。これはJobのUpdateViewで、JobCreateViewと同じ5つのフィールドを持ちます。
  • editという名前のルート"jobs/<slug:slug>/edit/"を作成します。

「実行」を押し、求人を開いて「編集」を押して保存すると、変更が反映された求人ページに戻ります。

自分で試してみよう

from django.views.generic import CreateView, DetailView, ListView, TemplateView

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"]

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

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