Django 教程 --- Django CRUD

Django 教程 --- Django CRUD_第1张图片

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

Django 教程 --- Django CRUD_第2张图片

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

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

使用示例说明如何创建和使用CRUD视图考虑一个名为的项目,其中geeksforgeeks有一个名为的应用geeks

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

# 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

创建此模型后,我们需要运行两个命令以便为同一数据库创建数据库

Python manage.py makemigrations
Python manage.py migrate

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

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

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

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

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

Django 教程 --- Django CRUD_第3张图片

检索视图

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

列表显示

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

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

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

{% endfor %}

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

Django 教程 --- Django CRUD_第4张图片

详细视图

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

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

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

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

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

让我们检查一下http:// localhost:8000/1上的内容。

Django 教程 --- Django CRUD_第5张图片

更新视图

更新视图是一种视图(逻辑),用于使用一些其他详细信息从数据库更新表的特定实例。它用于更新数据库中的小肠,例如,更新geeksforgeeks上的文章。
geeks/views.py

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)

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

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

geeks/templates/detail_view.html

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

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

Django 教程 --- Django CRUD_第6张图片

删除检视

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

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)

现在,一个URL映射到该视图与正则表达式id
geeks/urls.py

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

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

一切就绪,现在让我们检查其是否正常运行,请访问

http:// localhost:8000/2/delete

Django 教程 --- Django CRUD_第7张图片

Django 教程 --- Django CRUD_第8张图片

你可能感兴趣的:(Django 教程 --- Django CRUD)