Menu
CoddyTech

Thiết lập người đăng

Thuộc phần View dựa trên lớp trong hành trình Django của Coddy. Bài học 15 trên 18.

Mỗi Job đều có trường posted_by, còn công việc mới thì để trống trường này. Trường đó không được là một trường của biểu mẫu, nếu không thì bất kỳ ai cũng có thể đăng bài dưới tên người khác. View sẽ điền trường này.

Với một biểu mẫu hợp lệ, view chỉnh sửa gọi form_valid(form), hàm này lưu bản ghi rồi chuyển hướng. Hãy ghi đè hàm này để thay đổi bản ghi trước. Một trang công thức lưu mỗi bài đánh giá vào công thức có URL tương ứng, recipes/<slug:slug>/review/:

class ReviewCreateView(LoginRequiredMixin, CreateView):
    model = Review
    fields = ["stars", "text"]

    def form_valid(self, form):
        recipe = get_object_or_404(Recipe, slug=self.kwargs["slug"])
        form.instance.recipe = recipe
        return super().form_valid(form)

form.instance là bản ghi chưa được lưu. self.kwargs chứa các đối số trên URL; chỉ ví dụ này cần đến nó để tìm công thức. Hãy đặt trường của bạn, rồi để super().form_valid(form) lưu và chuyển hướng. Nếu đặt trường sau super(), bản ghi đã được lưu mà chưa có giá trị đó.

challenge icon

Thử thách

Dễ

Trong JobCreateView, ghi đè form_valid() để posted_by của công việc mới là người dùng đã đăng nhập. Không đưa posted_by vào fields.

Đăng nhập bằng tài khoản grace (coddy-pass-123) rồi đăng tin tuyển dụng. Trang của tin sẽ hiển thị by grace sau ngày đăng.

Tự làm thử

from django.contrib.auth.mixins import LoginRequiredMixin
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(LoginRequiredMixin, CreateView):
    model = Job
    fields = ["title", "company", "city", "salary", "description"]


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


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

Tất cả bài học trong View dựa trên lớp

Tự luyện tập: Playground Django