Django教程-基于 Django 类的通用视图
Django教程-基于 Django 类的通用视图
gh_1d7504e4dee1
回复:python,领取Python面试题。分享Python教程,Python架构师教程,Python爬虫,Python编程视频,Python脚本,Pycharm教程,Python微服务架构,Python分布式架构,Pycharm注册码。
基于函数的视图
它易于理解且易于使用。
它提供了显式的代码流程。
直接使用装饰器。
基于类的视图
它遵循 Django 的 DRY 约定。
我们可以使用 Mixin 扩展基于类的视图,并根据需求添加更多功能。
它允许继承另一个类,可以针对各种用例进行修改。
资源分享
使用基于类的视图执行 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
makemigrations
python
manage
.py
migrate
from
django.forms
import
fields
from
.models
import
Employee
from
django
import
forms
class
EmployeeForm
(forms.ModelForm)
:
class
Meta
:
# To specify the model to be used to create form
model = Employee
# It includes all the fields of model
fields =
’__all__’
实现基于类的视图
from
django.http
import
HttpResponse
def
function_view
(request)
:
if
request.method ==
’GET’
:
# View logic will place here
return
HttpResponse(
’response’
)
from
django.http
import
HttpResponse
from
django.views
import
View
class
NewView
(View)
:
def
get
(self, request)
:
# View logic will place here
return
HttpResponse(
’response’
)
# urls.py
from
django.urls
import
path
from
myapp.views
import
NewView
urlpatterns = [
path(
’about/’
, NewView.as_view()),
]
创建视图
注意 - employee_form.html 文件应包含在 template/app_name/employee_form.html 中。在我们的示例中,文件位置是 template/sampleapp/employee_form.html。
from
.models
import
Employee
from
.forms
import
EmployeeForm
from
django.views.generic.edit
import
CreateView
class
EmployeeCreate
(CreateView)
:
model = Employee
fields =
’__all__’
from
django.urls
import
path
from
.views
import
EmployeeCreate
urlpatterns = [
path(
’’
, EmployeeCreate.as_view(), name =
’EmployeeCreate’
)
]
检索视图
from
django.views.generic.list
import
ListView
class
EmployeeRetrieve
(ListView)
:
model = Employee
from
django.urls
import
path
from
.views
import
EmployeeCreate, EmployeeRetrieve
urlpatterns = [
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
DetailView
class
EmployeeDetail
(DetailView)
:
model = Employee
from
django.urls
import
path
from
.views
import
EmployeeCreate, EmployeeDetail, EmployeeRetrieve
urlpatterns = [
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
UpdateView
class
EmployeeUpdate
(UpdateView)
:
model = Employee
from django.urls
import
path
from .views
import
EmployeeCreate, EmployeeDetail, EmployeeRetrieve, EmployeeUpdate, EmployeeDelete
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
’)
]
删除视图
from
django.views.generic.edit DeleteView
class
EmployeeDelete
(DeleteView)
:
model = Employee
# here we can specify the URL
# to redirect after successful deletion
success_url =
’/’
from
django.urls
import
path
from
.views
import
EmployeeCreate, EmployeeDetail, EmployeeRetrieve, EmployeeUpdate, EmployeeDelete
urlpatterns = [
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, render
from
django.urls
import
reverse, reverse_lazy
from
django.contrib
import
messages
from
.models
import
Employee
from
.forms
import
EmployeeForm
from
django.views.generic.edit
import
CreateView, DeleteView, UpdateView
from
django.views.generic.list
import
ListView
from
django.views.generic.detail
import
DetailView
class
EmployeeCreate
(CreateView)
:
model = Employee
fields =
’__all__’
success_url = reverse_lazy(
’sampleapp: EmployeeRetrieve’
)
class
EmployeeRetrieve
(ListView)
:
model = Employee
success_url = reverse_lazy(
’sampleapp: EmployeeRetrieve’
)
class
EmployeeDetail
(DetailView)
:
model = Employee
success_url = reverse_lazy(
’sampleapp: EmployeeRetrieve’
)
class
EmployeeUpdate
(UpdateView)
:
model = Employee
template_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 deletion
success_url =
’/’
"""Hello URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path(’’, views.home, name=’home’)
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path(’’, Home.as_view(), name=’home’)
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path(’blog/’, include(’blog.urls’))
"""
from
django.contrib
import
admin126459646
from
django.urls
import
path
from
django.urls.conf
import
include
urlpatterns = [
path(
’admin126459646/’
, admin126459646.site.urls),
path(
’’
, include((
’sampleapp.urls’
), namespace=
’sampleapp’
))
]
from django.urls
import
path
from .views
import
EmployeeCreate, EmployeeDetail, EmployeeRetrieve, EmployeeUpdate, EmployeeDelete
app_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/bootstrap@5.0.2/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/bootstrap@5.0.2/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 %}
结论
-
Pandas50个高级操作,秀起来!
-
Django教程-Django on_delete参数
-
Python 3.11 的那些高效新特性!
-
2023年血糖新标准公布,不是3.9-6.1,快来看看你的血糖正常吗? 2023-02-07
-
2023年各省最新电价一览!8省中午执行谷段电价! 2023-01-03
-
GB 55009-2021《燃气工程项目规范》(含条文说明),2022年1月1日起实施 2021-11-07
-
PPT导出高分辨率图片的四种方法 2022-09-22
-
2023年最新!国家电网27家省级电力公司负责人大盘点 2023-03-14
-
全国消防救援总队主官及简历(2023.2) 2023-02-10
-
盘点 l 中国石油大庆油田现任领导班子 2023-02-28
-
我们的前辈!历届全国工程勘察设计大师完整名单! 2022-11-18
-
关于某送变电公司“4·22”人身死亡事故的快报 2022-04-26
