Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách thêm UpdateView trong Django


UpdateView là generic view tích hợp sẵn cho phép cập nhật đối tượng model từ frontend, tương tự trang admin.

Triển khai nhanh

  1. Model: Student(name, standard, section)

  2. Form: ModelForm cho model Student.

  3. URL: path('student/edit//', StudentUpdateView.as_view(), name='update')

  4. View:

    class StudentUpdateView(UpdateView):
        model = Student
        fields = '__all__'
        template_name = 'update_view.html'
        success_url = '/success/'
  5. Template update_view.html render form với {{ form }}.

Kết quả

Truy cập /student/edit/1/ → form sửa thông tin sinh viên → bấm Submit → redirect success.