Django's common view reduces the monotony of development by abstracting out some of the code and patterns commonly used in view development, so that you can quickly write common view functions without having to write a lot of code. The preceding code is rewritten with a common view. To use a common view, we need to do a few things:
- Modify Urlconf
- Writing a view function based on a common view
1, modify the urlconf
fromDjango.conf.urlsImportPatterns,url fromBlog.viewsImport*Urlpatterns= Patterns ("', the URL (r'^$', Indexview.as_view (), name='Index'), url (r'^edit/$', edit,name='Edit'), url (r'^(? p<pk>\d+)/$', Detailview.as_view (), name='Detail'),///Here the ID becomes PK)
2. Modify the View
fromDjango.shortcutsImportRender,get_object_or_404,redirect fromBlog.modelsImportBlog,postform fromDjango.viewsImportGenericImportdatetimeclassIndexview (Generic. ListView): Template_name='blog/index.html'Context_object_name='Blogs' defGet_queryset (self):returnBlog.objects.all ()classDetailView (Generic. DetailView): Model=Blog template_name='blog/detail.html' defedit (Request):ifrequest.method=='POST': Form=Postform (Request. POST)ifform.is_valid (): Post=form.save (commit=False) Post.user=Request.user Post.created_time=Datetime.datetime.now () post.published_time=Datetime.datetime.now () post.save ( )returnRender (Request,'blog/detail.html',{'Blog':p OST}) Else: Form=Postform ()returnRender (Request,'blog/edit.html',{'form': Form})
We used two common views: ListView and DetailView
ListView: Display Object list
DetailView: Displays a property detail for an object
If we don't specify template_namein the general view function, Django will default to find <app name>/<model name>_detail.html and <app name>/<model name>_list.html templates.
OK, the general view configuration is complete.
A common view of Django Learning (generic views)