📜  Django CRUD(创建、检索、更新、删除)基于函数的视图

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

Django CRUD(创建、检索、更新、删除)基于函数的视图

Django 是一个基于 Python 的 Web 框架,它允许您快速创建 Web 应用程序,而不会出现您通常会在其他框架中发现的所有安装或依赖问题。 Django 基于 MVT(模型视图模板)架构,围绕 CRUD(创建、检索、更新、删除)操作。 CRUD 可以最好地解释为构建 Django Web 应用程序的一种方法。一般来说,CRUD 意味着对数据库中的表执行创建、检索、更新和删除操作。让我们讨论一下 CRUD 的真正含义,

Untitled-Diagram-316

创建- 在数据库的表中创建或添加新条目。
检索– 以列表形式读取、检索、搜索或查看现有条目(列表视图)或详细检索特定条目(详细视图)
更新——更新或编辑数据库表中的现有条目
删除– 删除、停用或移除数据库表中的现有条目

Django CRUD(创建、检索、更新、删除)基于函数的视图

如何使用示例创建和使用 CRUD 视图的说明。考虑一个名为 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.shortcuts import render
 
# relative import of forms
from .models import GeeksModel
from .forms import GeeksForm
 
 
def create_view(request):
    # dictionary for initial data with
    # field names as keys
    context ={}
 
    # add the dictionary during initialization
    form = GeeksForm(request.POST or None)
    if form.is_valid():
        form.save()
         
    context['form']= form
    return render(request, "create_view.html", context)


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


Python3
from django.shortcuts import render
 
# relative import of forms
from .models import GeeksModel
 
 
def list_view(request):
    # dictionary for initial data with
    # field names as keys
    context ={}
 
    # add the dictionary during initialization
    context["dataset"] = GeeksModel.objects.all()
         
    return render(request, "list_view.html", context)


html
      {% for data in dataset %}.       {{ data.title }}
    {{ data.description }}
    
      {% endfor %}  


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


Python3
from django.shortcuts import render
 
# relative import of forms
from .models import GeeksModel
 
# pass id attribute from urls
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)


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


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 }}


Python3
from django.shortcuts import (get_object_or_404,
                              render,
                              HttpResponseRedirect)
 
from .models import GeeksModel
 
 
# delete view for details
def delete_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)
 
 
    if request.method =="POST":
        # delete object
        obj.delete()
        # after deleting redirect to
        # home page
        return HttpResponseRedirect("/")
 
    return render(request, "delete_view.html", context)


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


html
         
                 {% csrf_token %}         Are you want to delete this item ?                  Cancel     


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

Python manage.py makemigrations
Python manage.py migrate

现在我们将为这个模型创建一个 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",
        ]

创建视图

创建视图是指在数据库中创建表的实例的视图(逻辑)。这就像从用户那里获取输入并将其存储在指定的表中一样。
在 geeks/views.py 中,

Python3

from django.shortcuts import render
 
# relative import of forms
from .models import GeeksModel
from .forms import GeeksForm
 
 
def create_view(request):
    # dictionary for initial data with
    # field names as keys
    context ={}
 
    # add the dictionary during initialization
    form = GeeksForm(request.POST or None)
    if form.is_valid():
        form.save()
         
    context['form']= form
    return render(request, "create_view.html", context)

在 templates/create_view.html 中创建模板,

html

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

现在访问 http://localhost:8000/

django-create-view-function-based

要检查基于函数的创建视图的完整实现,请访问创建视图 - 基于函数的视图 Django。

检索视图

检索视图基本上分为两种视图,详细视图和列表视图。

列表显示

列表视图是指以特定顺序列出数据库中表的所有或特定实例的视图(逻辑)。它用于在单个页面或视图上显示多种类型的数据,例如电子商务页面上的产品。
在 geeks/views.py 中,

Python3

from django.shortcuts import render
 
# relative import of forms
from .models import GeeksModel
 
 
def list_view(request):
    # dictionary for initial data with
    # field names as keys
    context ={}
 
    # add the dictionary during initialization
    context["dataset"] = GeeksModel.objects.all()
         
    return render(request, "list_view.html", context)

在 templates/list_view.html 中创建模板,

html

      {% for data in dataset %}.       {{ data.title }}
    {{ data.description }}
    
      {% endfor %}  

现在访问 http://localhost:8000/

django-listview-function-based

要检查基于函数的列表视图的完整实现,请访问列表视图 - 基于函数的视图 Django

详细视图

详细视图是指一种视图(逻辑),用于显示数据库中表的特定实例以及所有必要的详细信息。它用于在单个页面或视图上显示多种类型的数据,例如用户的个人资料。
在 geeks/views.py 中,

Python3

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

让我们为其创建一个视图和模板。在 geeks/views.py 中,

Python3

from django.shortcuts import render
 
# relative import of forms
from .models import GeeksModel
 
# pass id attribute from urls
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)

在templates/Detail_view.html中创建一个模板,

html

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

让我们检查一下 http://localhost:8000/1 上有什么

django-detail-view-demo1

要检查基于函数的详细视图的完整实现,请访问详细视图 - 基于函数的视图 Django

更新视图

更新视图是指一种视图(逻辑),用于从数据库中更新表的特定实例,并提供一些额外的细节。它用于更新数据库中的条目,例如,更新 geeksforgeeks 上的文章。
在 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

删除视图

删除视图是指从数据库中删除表的特定实例的视图(逻辑)。它用于删除数据库中的条目,例如,删除 geeksforgeeks 上的文章。
在极客/views.py

Python3

from django.shortcuts import (get_object_or_404,
                              render,
                              HttpResponseRedirect)
 
from .models import GeeksModel
 
 
# delete view for details
def delete_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)
 
 
    if request.method =="POST":
        # delete object
        obj.delete()
        # after deleting redirect to
        # home page
        return HttpResponseRedirect("/")
 
    return render(request, "delete_view.html", context)

现在使用正则表达式 id 映射到该视图的 url,
在极客/urls.py

Python3

from django.urls import path
 
# importing views from views..py
from .views import delete_view
urlpatterns = [
    path('/delete', delete_view ),
]

删除视图模板包括一个简单的表单,用于确认用户是否要删除实例。在 geeks/templates/delete_view.html 中,

html

         
                 {% csrf_token %}         Are you want to delete this item ?                  Cancel     

一切准备就绪,现在让我们检查它是否工作,访问 http://localhost:8000/2/delete

django-删除视图

要检查基于函数的删除视图的完整实现,请访问删除视图 - 基于函数的视图 Django