English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In some cases, writing view code, as we saw earlier, can be really tedious. Imagine that you just need a static page or a list page. Django also provides a simple way to set up these simple views, called generic views.
Different from traditional views, generic views are classes without functions. Django also provides a set of class django.views.generic generic views, and each ordinary view is a class or inherits from one of these classes.
There are more than 10 generic classes−
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ru.oldtoolbag.com # Date : 2020-08-08 >>> import django.views.generic >>> dir(django.views.generic) ['ArchiveIndexView', 'CreateView', 'DateDetailView', 'DayArchiveView', 'DeleteView', 'DetailView', 'FormView', 'GenericViewError', 'ListView', 'MonthArchiveView', 'RedirectView', 'TemplateView', 'TodayArchiveView', 'UpdateView', 'View', 'WeekArchiveView', 'YearArchiveView', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'base', 'dates', 'detail', 'edit', 'list'
You can use generic views. Let's look at some examples to see how it works.
Let's publish a static page from the 'static.html' template.
our static.html −
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ru.oldtoolbag.com # Date : 2020-08-08 <html> <body> This is a static page!!! </body> </html>
Если мы будем поступать так, как мы изучали раньше, нам придётся изменить myapp/views.py −
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ru.oldtoolbag.com # Date : 2020-08-08 from django.shortcuts import render def static(request): return render(request, 'static.html', {})
myapp/urls.py будет выглядеть так −
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ru.oldtoolbag.com # Date : 2020-08-08 from django.conf.urls import patterns, url urlpatterns = patterns("myapp.views", url(r'^static/', 'static', name='static'),)
Лучший способ - использовать generics-виды. Для этого наш myapp/views.py станет выглядеть так −
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ru.oldtoolbag.com # Date : 2020-08-08 from django.views.generic import TemplateView class StaticView(TemplateView): template_name = "static.html"
А наш myapp/urls.py будет выглядеть так −
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ru.oldtoolbag.com # Date : 2020-08-08 from myapp.views import StaticView from django.conf.urls import patterns urlpatterns = patterns("myapp.views", (r'^static/', StaticView.as_view()),) , StaticView.as_view()),)
При доступе к /myapp/static вы получите −
Для достижения того же результата мы можем выполнить следующие действия −
Не нужно изменять views.py Измените файл url.py на -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ru.oldtoolbag.com # Date : 2020-08-08 from django.views.generic import TemplateView from django.conf.urls import patterns, url urlpatterns = patterns("myapp.views", url(r'^static/', TemplateView.as_view(template_name='static.html')),)
Как вы видите, нужно только изменить второй метод в файле url.py.
Мы хотим перечислить все элементы в модели Dreamreal. Это делает использование generics-вида ListView легко. Редактируйте файл url.py и обновите его -
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ru.oldtoolbag.com # Date : 2020-08-08 from django.views.generic import ListView from django.conf.urls import patterns, url urlpatterns = patterns( "myapp.views", url(r'^dreamreals/', ListView.as_view(model=Dreamreal, template_name = "dreamreal_list.html")),
Важно отметить, что на этом этапе переменная проходит от generics视图 к шаблону object_list. Если вы хотите использовать свое имя, вам нужно добавить параметр context_object_name к методу as_view. Затем url.py становится таким:
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ru.oldtoolbag.com # Date : 2020-08-08 from django.views.generic import ListView from django.conf.urls import patterns, url urlpatterns = patterns("myapp.views", url(r'^dreamreals/', ListView.as_view(), template_name = "dreamreal_list.html")), model = Dreamreal, context_object_name = "dreamreals_objects",)
Затем связанный шаблон станет −
# Filename : example.py # Copyright : 2020 By w3codebox # Author by : ru.oldtoolbag.com # Date : 2020-08-08 {% extends "main_template.html" %} {% block content %} Dreamreals:<p> {% for dr in object_list %} {{ dr.name }}</p> {% endfor %} {% endblock %}
Адрес посещения /myapp/dreamreals/ приведет к следующей странице −