CreateView
Thuộc phần View dựa trên lớp trong hành trình Django của Coddy. Bài học 10 trên 18.
Menu có liên kết Post a job nhưng chưa có trang nào phía sau. Trang thêm một hàng luôn dùng cùng một đoạn code: hiển thị biểu mẫu trống, kiểm tra dữ liệu đã gửi, lưu dữ liệu rồi chuyển hướng. CreateView chính là đoạn code đó, cùng với một ModelForm mà nó tạo giúp bạn:
from django.views.generic import CreateView
class RecipeCreateView(CreateView):
model = Recipe
fields = ["title", "cuisine", "minutes"]fields liệt kê các trường của biểu mẫu, giống như Meta của ModelForm. Mẫu mặc định là recipes/recipe_form.html, trong đó biểu mẫu có tên form. Nếu dữ liệu không hợp lệ, trang sẽ hiển thị lại biểu mẫu cùng các lỗi và không lưu gì cả.
Đặt tuyến "recipes/new/" phía trên "recipes/<slug:slug>/". Django dùng tuyến khớp đầu tiên. new là một slug hợp lệ, nên tuyến slug đặt phía trên tuyến này sẽ bắt /recipes/new/ và trả về lỗi 404.
Thử thách
Trung bìnhTạo trang phía sau Post a job bằng mẫu có sẵn jobs/job_form.html.
- Trong
jobs/views.py, thêmJobCreateView, mộtCreateViewchoJobvới các trườngtitle,company,city,salaryvàdescription. - Trong
jobs/urls.py, thêm tuyến đường"jobs/new/"có têncreate.
Đăng tin tuyển dụng: tin được lưu, sau đó Django dừng lại với lỗi No URL to redirect to, bài học tiếp theo sẽ khắc phục lỗi này.
Tự làm thử
from django.views.generic import 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
Tất cả bài học trong View dựa trên lớp
Tự luyện tập: Playground Django