Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเพิ่ม UpdateView ใน Django


UpdateView เป็น View ใน Django ใช้แก้ไขข้อมูลโมเดลจาก Frontend เป็น built-in view ใช้ง่าย คล้ายหน้า Admin ในการแก้ไข บทความนี้สาธิตการใช้ UpdateView

ตัวอย่าง

สร้างโปรเจกต์ Django และแอป ชื่อ "tutorial11" และ "modelFormsDemo"

ใน settings.py เพิ่มแอป:

INSTALLED_APPS+ = ['modelFormsDemo']

ใน urls.py ของโปรเจกต์ include urls ของแอป:

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('modelFormsDemo.urls'))
]

ใน urls.py ของแอป:

from django.urls import path, include
from . import views
urlpatterns = [
    path('', views.home, name="home"),
    path('student/edit//', views.StudentUpdateView.as_view(), name="update"),
    path('success/', views.success, name='success')
]

สร้าง 3 URLs: หน้าแรก, UpdateView สำหรับแก้ไข, success สำหรับ redirect

ใน models.py:

from django.db import models
class Student(models.Model):
    name = models.CharField(max_length=100)
    standard = models.CharField(max_length=100)
    section = models.CharField(max_length=100)

ใน views.py:

from django.shortcuts import render
from .forms import StudentForm
from django.views.generic.edit import UpdateView
from .models import Student
from django.urls import reverse_lazy

def home(request):
    if request.method == 'POST':
        form = StudentForm(request.POST)
        if form.is_valid():
            form.save()
    stuForm = StudentForm()
    return render(request, 'home.html', {"stu_form": stuForm})

class StudentUpdateView(UpdateView):
    model = Student
    fields = "__all__"
    template_name = 'update_view.html'
    success_url = '/success/'

def success(request):
    return render(request, 'success.html')

ใน forms.py:

from django import forms
from .models import Student
class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = ['name', 'standard', 'section']

สร้าง templates และไฟล์ home.html, update_view.html, success.html

ใน home.html และ update_view.html:

<!DOCTYPE html> <html>
<head> <title>TUT</title> </head>
<body>
    {% for fm in stu_form %}
    <form method="post">
        {% csrf_token %}
        {{fm.errors}}<br>
        {{fm.label}}:{{fm}}<br>
    {% endfor %}
    <button type="submit">Submit</button>
    </form>
</body> </html>

ใน success.html:

<!DOCTYPE html> <html>
<head> <title>TUT</title> </head>
<body>
    <h2>Success</h2>
</body> </html>

เอาต์พุต

Home.html – วิธีเพิ่ม UpdateView ใน Django

เข้า https://127.0.0.1:8000/student/edit/(student object id)/ จะเห็น update_view.html

Update_view.html – วิธีเพิ่ม UpdateView ใน Django