如何在Django中新增UpdateView?
UpdateView是Django中的一個檢視,用於從前端更新任何模型資料。它是一個內建檢視,易於應用。它在更新檢視方面類似於管理頁面。在本文中,我們將透過一個示例演示如何在Django中使用UpdateView。
首先,建立一個Django專案和一個應用。我建立的專案名為**"tutorial11"**,應用名為**"modelFormsDemo"**。
現在,讓我們做一些基本的事情。
在**settings.py**中新增應用。
INSTALLED_APPS+ = ['modelFormsDemo']
在專案的**urls.py**中,包含應用的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') ]
這裡我們建立了三個url;一個用於渲染前端,一個用於更新的UpdateView,以及更新後重定向的success。
示例
在**models.py**中,新增以下內容:
from django.db import models # Create your models here 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 # Create your views here. 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**:
現在,如果您訪問http://127.0.0.1:8000/student/edit/(學生物件ID)/,您將看到我們的update_view.html。
**Update_view.html**: