Django教程-基于 Django 类的通用视图
基于函数的视图
它易于理解且易于使用。
它提供了显式的代码流程。
直接使用装饰器。
基于类的视图
它遵循 Django 的 DRY 约定。
我们可以使用 Mixin 扩展基于类的视图,并根据需求添加更多功能。
它允许继承另一个类,可以针对各种用例进行修改。
👉点击领取:最全Python资料合集
使用基于类的视图执行 CRUD(创建、检索、更新、删除)
from django.db import models# Create your models here.class Employee(models.Model):first_name = models.CharField(max_length=30)last_name = models.CharField(max_length=30)mobile = models.CharField(max_length=10)email = models.EmailField()def __str__(self):return "%s %s" % (self.first_name, self.last_name)
python manage.py makemigrationspython manage.py migrate
from django.forms import fieldsfrom .models import Employeefrom django import formsclass EmployeeForm(forms.ModelForm):class Meta:# To specify the model to be used to create formmodel = Employee# It includes all the fields of modelfields = '__all__'
实现基于类的视图
from django.http import HttpResponsedef function_view(request):if request.method == 'GET':# View logic will place herereturn HttpResponse('response')
from django.http import HttpResponsefrom django.views import Viewclass NewView(View):def get(self, request):# View logic will place herereturn HttpResponse('response')
# urls.pyfrom django.urls import pathfrom myapp.views import NewViewurlpatterns = [path('about/', NewView.as_view()),]
创建视图
注意 - employee_form.html 文件应包含在 template/app_name/employee_form.html 中。在我们的示例中,文件位置是 template/sampleapp/employee_form.html。
from .models import Employeefrom .forms import EmployeeFormfrom django.views.generic.edit import CreateViewclass EmployeeCreate(CreateView):model = Employeefields = '__all__'
from django.urls import pathfrom .views import EmployeeCreateurlpatterns = [path('', EmployeeCreate.as_view(), name = 'EmployeeCreate')]
检索视图
from django.views.generic.list import ListViewclass EmployeeRetrieve(ListView):model = Employee
from django.urls import pathfrom .views import EmployeeCreate, EmployeeRetrieveurlpatterns = [path('', EmployeeCreate.as_view(), name = 'EmployeeCreate'),path('retrieve/', EmployeeRetrieve.as_view(), name = 'EmployeeRetrieve')]
{% extends 'base.html' %}{% block content %}<ul class="nav flex-column"><!-- Iterate over object_list -->{% for object in object_list %}<!-- Display Objects --><li class="nav-item">First Name: {{ object.first_name }}</li><li class="nav-item">Last Name: {{ object.last_name }}</li><li class="nav-item">Mobile: {{ object.mobile }}</li><li class="nav-item"> Email: {{ object.email }}</li><hr/><!-- If object_list is empty -->{% empty %}<li class="nav-item">No objects Find</li>{% endfor %}</ul>{% endblock content %}
详细视图
from django.views.generic.detail import DetailViewclass EmployeeDetail(DetailView):model = Employee
from django.urls import pathfrom .views import EmployeeCreate, EmployeeDetail, EmployeeRetrieveurlpatterns = [path('', EmployeeCreate.as_view(), name = 'EmployeeCreate'),path('retrieve/', EmployeeRetrieve.as_view(), name = 'EmployeeRetrieve'),path('retrieve/<int:pk>', EmployeeDetail.as_view(), name = 'EmployeeDetail')]
{% extends 'base.html' %}{% block content %}<h1>{{ object.first_name }} {{object.last_name}}</h1><p>{{ object.email }}</p><p>{{ object.mobile }}</p>{% endblock content %}
更新视图
from django.views.generic.edit import UpdateViewclass EmployeeUpdate(UpdateView):model = Employee
from django.urls import pathfrom .views import EmployeeCreate, EmployeeDetail, EmployeeRetrieve, EmployeeUpdate, EmployeeDeleteurlpatterns = [path('', EmployeeCreate.as_view(), name = 'EmployeeCreate'),path('retrieve/', EmployeeRetrieve.as_view(), name = 'EmployeeRetrieve'),path('<int:pk>', EmployeeDetail.as_view(), name = 'EmployeeDetail'),path('<int:pk>/update/', EmployeeUpdate.as_view(), name = 'EmployeeUpdate'),path('<int:pk>/delete/', EmployeeDelete.as_view(), name = 'EmployeeDelete')]
删除视图
from django.views.generic.edit DeleteViewclass EmployeeDelete(DeleteView):model = Employee# here we can specify the URL# to redirect after successful deletionsuccess_url = '/'
from django.urls import pathfrom .views import EmployeeCreate, EmployeeDetail, EmployeeRetrieve, EmployeeUpdate, EmployeeDeleteurlpatterns = [path('', EmployeeCreate.as_view(), name = 'EmployeeCreate'),path('retrieve/', EmployeeRetrieve.as_view(), name = 'EmployeeRetrieve'),path('<int:pk>', EmployeeDetail.as_view(), name = 'EmployeeDetail'),path('<pk>/update/', EmployeeUpdate, name = 'EmployeeUpdate'),path('<pk>/delete/', EmployeeDelete, name = 'EmployeeDelete')]
{% extends 'base.html' %}{% block content %}<form method="post">{% csrf_token %}<p>Are you sure you want to delete "{{ object }}"?</p><input type="submit" value="Confirm"></form>{% endblock content %}
代码
from django.shortcuts import redirect, renderfrom django.urls import reverse, reverse_lazyfrom django.contrib import messagesfrom .models import Employeefrom .forms import EmployeeFormfrom django.views.generic.edit import CreateView, DeleteView, UpdateViewfrom django.views.generic.list import ListViewfrom django.views.generic.detail import DetailViewclass EmployeeCreate(CreateView):model = Employeefields = '__all__'success_url = reverse_lazy('sampleapp: EmployeeRetrieve')class EmployeeRetrieve(ListView):model = Employeesuccess_url = reverse_lazy('sampleapp: EmployeeRetrieve')class EmployeeDetail(DetailView):model = Employeesuccess_url = reverse_lazy('sampleapp: EmployeeRetrieve')class EmployeeUpdate(UpdateView):model = Employeetemplate_name_suffix = '_update_form'fields = '__all__'success_url = reverse_lazy('sampleapp: EmployeeRetrieve')# def get_success_url(self):class EmployeeDelete(DeleteView):model = Employee# here we can specify the URL# to redirect after successful deletionsuccess_url = '/'
"""Hello URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see:https://docs.djangoproject.com/en/3.1/topics/http/urls/Examples:Function views1. Add an import: from my_app import views2. Add a URL to urlpatterns: path('', views.home, name='home')Class-based views1. Add an import: from other_app.views import Home2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')Including another URLconf1. Import the include() function: from django.urls import include, path2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))"""from django.contrib import adminfrom django.urls import pathfrom django.urls.conf import includeurlpatterns = [path('admin/', admin.site.urls),path('', include(('sampleapp.urls'), namespace='sampleapp'))]
from django.urls import pathfrom .views import EmployeeCreate, EmployeeDetail, EmployeeRetrieve, EmployeeUpdate, EmployeeDeleteapp_name = 'sampleapp'urlpatterns = [path('', EmployeeCreate.as_view(), name = 'EmployeeCreate'),path('retrieve/', EmployeeRetrieve.as_view(), name = 'EmployeeRetrieve'),path('<int:pk>', EmployeeDetail.as_view(), name = 'EmployeeDetail'),path('<int:pk>/update/', EmployeeUpdate.as_view(), name = 'EmployeeUpdate'),path('<int:pk>/delete/', EmployeeDelete.as_view(), name = 'EmployeeDelete')]
<!doctype html><html lang="en"><head><!-- Required meta tags --><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><!-- Bootstrap CSS --><link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"><title>Register Page</title></head><body><div class = 'col-md-8'>{% if messages %}<ul>{% for message in messages %}<div class = 'alert alert-{{message.tags}}'>{{ message }}</div>{% endfor %}</ul>{% endif %}</div>{% block content %}<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>{% endblock content %}</body></html>
{% extends 'base.html' %}{% block content %}<table class="table table-borderless"><thead class="border-bottom font-weight-bold"><tr><td>First Name</td><td>Last Name</td><td>Mobile</td><td>Email</td>{% comment %} <a href="{% url 'EmployeeRetrieve' %}" class="btn btn-outline-success"><i class="fas fa-plus"></i> Add New {% endcomment %}</a></td></tr></thead>{% for object in object_list %}<!-- Display Objects --><tr><td>{{ object.first_name }}</td><td> {{object.last_name }}</td><td> {{object.mobile }}</td><td>{{object.email }} </td><td><td><button><a href = '/{{object.pk}}/delete' class = 'class="btn text-secondary px-0'> Delete</a></button></td><td><button><a href = '/{{object.pk}}/update' class = 'class="btn text-secondary px-0'> Update</a></button></td>{% endfor %}</table>
{% extends 'base.html' %}{% block content %}<h1>{{ object.first_name }} {{object.last_name}}</h1><p>{{ object.email }}</p><p>{{ object.mobile }}</p><td><button><a href = '/{{object.pk}}/delete' class = 'class="btn text-secondary px-0'> Delete</a></button></td><td><button><a href = '/{{object.pk}}/update' class = 'class="btn text-secondary px-0'> Update</a></button></td>{% endblock content %}
{% extends 'base.html' %}{% block content %}<form method="post">{% csrf_token %}{{ form.as_p }}<input type="submit" value="Update"></form>{% endblock content %}
{% extends 'base.html' %}{% block content %}<form method="post">{% csrf_token %}<p>Are you sure you want to delete "{{ object }}"?</p><input type="submit" value="Confirm"></form>{% endblock content %}