UpdateView
Thuộc phần View dựa trên lớp trong hành trình Django của Coddy. Bài học 12 trên 18.
Người đăng cần chỉnh sửa công việc của họ. Chỉnh sửa một hàng cũng giống như tạo một hàng, ngoại trừ việc biểu mẫu đã có sẵn dữ liệu và khi lưu, hàng đó sẽ thay đổi thay vì thêm hàng mới. UpdateView làm được cả hai việc. Một trang web công thức nấu ăn:
class RecipeUpdateView(UpdateView):
model = Recipe
fields = ["title", "cuisine", "minutes"]
# urls.py
path("recipes/<int:pk>/change/", views.RecipeUpdateView.as_view(), name="change")Cách tìm hàng giống như DetailView, bằng pk hoặc slug trong URL, và trả về lỗi 404 khi không có hàng nào khớp. Sau khi lưu, trang sẽ chuyển đến nơi CreateView chuyển đến: success_url hoặc get_absolute_url() của hàng.
Nó dùng chung recipes/recipe_form.html với CreateView và thêm hàng đó dưới tên object, vì vậy {% if object %} chỉ đúng khi đang chỉnh sửa. Bắt buộc phải có fields: Django sẽ không tự đoán khách truy cập được phép thay đổi những trường nào.
Thử thách
DễTrang việc làm giờ có liên kết Edit. Hãy tạo trang đích cho liên kết này.
- Trong
jobs/views.py, thêmJobUpdateView, mộtUpdateViewcủaJobvới cùng năm trường nhưJobCreateView. - Trong
jobs/urls.py, thêm tuyến đường"jobs/<slug:slug>/edit/"có tênedit.
Mở một việc làm, nhấn Edit rồi lưu: bạn sẽ quay lại trang việc làm với thay đổi của mình.
Tự làm thử
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"]
Tất cả bài học trong View dựa trên lớp
Tự luyện tập: Playground Django