A common view of Django Learning (generic views)

Source: Internet
Author: User

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:

    1. Modify Urlconf
    2. 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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.