📜  更新视图——基于函数的视图 Django

📅  最后修改于: 2022-05-13 01:54:26.720000             🧑  作者: Mango

更新视图——基于函数的视图 Django

更新视图是指一种视图(逻辑),用于从数据库中更新表的特定实例,并提供一些额外的细节。它用于更新数据库中的条目,例如,更新 geeksforgeeks 上的文章。所以更新视图必须在表单中显示旧数据,并让用户只从那里更新数据。 Django 为更新视图提供了非凡的支持,但让我们检查一下它是如何通过基于函数的视图手动完成的。本文围绕更新视图展开,其中涉及到 Django Forms、Django Models 等概念。

对于更新视图,我们需要一个包含一些模型和多个实例的项目,它们将被显示。基本上,更新视图是详细视图和创建视图的组合。

Django 更新视图——基于函数的视图

如何使用示例创建和使用更新视图的说明。考虑一个名为 geeksforgeeks 的项目,它有一个名为 geeks 的应用程序。

在你有一个项目和一个应用程序之后,让我们创建一个模型,我们将通过我们的视图创建它的实例。在 geeks/models.py 中,

Python3
# import the standard Django Model
# from built-in library
from django.db import models
  
# declare a new model with a name "GeeksModel"
class GeeksModel(models.Model):
 
    # fields of the model
    title = models.CharField(max_length = 200)
    description = models.TextField()
 
    # renames the instances of the model
    # with their title name
    def __str__(self):
        return self.title


Python3
from django import forms
from .models import GeeksModel
 
 
# creating a form
class GeeksForm(forms.ModelForm):
 
    # create meta class
    class Meta:
        # specify model to be used
        model = GeeksModel
 
        # specify fields to be used
        fields = [
            "title",
            "description"]


Python3
from django.urls import path
 
# importing views from views..py
from .views import update_view, detail_view
 
urlpatterns = [
    path('/', detail_view ),
    path('/update', update_view ),
]


Python3
from django.shortcuts import (get_object_or_404,
                              render,
                              HttpResponseRedirect)
 
# relative import of forms
from .models import GeeksModel
from .forms import GeeksForm
 
# after updating it will redirect to detail_View
def detail_view(request, id):
    # dictionary for initial data with
    # field names as keys
    context ={}
  
    # add the dictionary during initialization
    context["data"] = GeeksModel.objects.get(id = id)
          
    return render(request, "detail_view.html", context)
 
# update view for details
def update_view(request, id):
    # dictionary for initial data with
    # field names as keys
    context ={}
 
    # fetch the object related to passed id
    obj = get_object_or_404(GeeksModel, id = id)
 
    # pass the object as instance in form
    form = GeeksForm(request.POST or None, instance = obj)
 
    # save the data from the form and
    # redirect to detail_view
    if form.is_valid():
        form.save()
        return HttpResponseRedirect("/"+id)
 
    # add form dictionary to context
    context["form"] = form
 
    return render(request, "update_view.html", context)


HTML
         
                 {% csrf_token %}                    {{ form.as_p }}                
 


HTML
         {{ data.title }}
    {{ data.description }}


创建此模型后,我们需要运行两个命令才能为其创建数据库。

Python manage.py makemigrations
Python manage.py migrate

现在让我们使用 shell 创建这个模型的一些实例,运行表单 bash,

Python manage.py shell

输入以下命令

>>> from geeks.models import GeeksModel
>>> GeeksModel.objects.create(
                       title="title1",
                       description="description1").save()
>>> GeeksModel.objects.create(
                       title="title2",
                       description="description2").save()
>>> GeeksModel.objects.create(
                       title="title2",
                       description="description2").save()

现在我们已经为后端做好了一切准备。验证是否已从 http://localhost:8000/admin/geeks/geeksmodel/ 创建实例

django-Updateview-check-models-instances

现在我们将为这个模型创建一个 Django ModelForm。有关 modelform 的更多信息,请参阅本文 – Django ModelForm – 从模型创建表单。在 geeks 文件夹中创建文件 forms.py,

Python3

from django import forms
from .models import GeeksModel
 
 
# creating a form
class GeeksForm(forms.ModelForm):
 
    # create meta class
    class Meta:
        # specify model to be used
        model = GeeksModel
 
        # specify fields to be used
        fields = [
            "title",
            "description"]

对于 Update_view,需要一些标识来获取模型的特定实例。通常它是唯一的主键,例如id 。要指定这个标识,我们需要在 urls.py 中定义它。转到极客/urls.py,

Python3

from django.urls import path
 
# importing views from views..py
from .views import update_view, detail_view
 
urlpatterns = [
    path('/', detail_view ),
    path('/update', update_view ),
]

让我们用解释创建这些视图。在 geeks/views.py 中,

Python3

from django.shortcuts import (get_object_or_404,
                              render,
                              HttpResponseRedirect)
 
# relative import of forms
from .models import GeeksModel
from .forms import GeeksForm
 
# after updating it will redirect to detail_View
def detail_view(request, id):
    # dictionary for initial data with
    # field names as keys
    context ={}
  
    # add the dictionary during initialization
    context["data"] = GeeksModel.objects.get(id = id)
          
    return render(request, "detail_view.html", context)
 
# update view for details
def update_view(request, id):
    # dictionary for initial data with
    # field names as keys
    context ={}
 
    # fetch the object related to passed id
    obj = get_object_or_404(GeeksModel, id = id)
 
    # pass the object as instance in form
    form = GeeksForm(request.POST or None, instance = obj)
 
    # save the data from the form and
    # redirect to detail_view
    if form.is_valid():
        form.save()
        return HttpResponseRedirect("/"+id)
 
    # add form dictionary to context
    context["form"] = form
 
    return render(request, "update_view.html", context)

现在在模板文件夹中创建以下模板,
在 geeks/templates/update_view.html 中,

HTML

         
                 {% csrf_token %}                    {{ form.as_p }}                
 

在 geeks/templates/detail_view.html 中,

HTML

         {{ data.title }}
    {{ data.description }}

让我们检查一下是否一切正常,访问 http://localhost:8000/1/update。

django-update-view-

在这里您可以看到已经从实例中填充数据的表单,现在可以轻松地编辑和更新这些数据,让我们来看看

django-update-view-edit-data

点击更新并完成。

django-更新-查看-结果