Tutorial to create django app – P3

Tram Ho

Part 3 – Create views, templates. Convert view to class-based View


Lifecycle

Lifecycle

Add views

views.py:

Add routes

Add template

Default template set in  polls/templates/polls

  1. polls/templates/polls/index.html:

  1. polls/templates/polls/detail.html:

Want to change the template path => mysite/settings.py Undefined ????


=> 3 url transfer type:

  • Cattle type:

  • Type of name transfer of url: in the file  polls/urls.py  named  name='detail' => name is detail:

  • Type of transmission namespace polls and url name detail:

urls.py: more app_name = 'polls'


get_object_or_404 and render are shortcuts. Other spellings:

views.py



Series django first project

Add a Vote function form

polls/templates/polls/detail.html:

polls/views.py:


View result function

polls/views.py:

polls/templates/polls/results.html:

If there are 2 people submitting the exact same file at the same time => the voting result will only increase by 1 unit (expected to be 2) => Research https://docs.djangoproject.com/en/3.0/ref/models/expressions/#avoiding-race-conditions-using-f

class-based view

The views flow above work according to a very basic spec, which is generally taking requests with parameters, then querying and retrieving the template to return a response. Django converts this flow (Function Based Views) into another format (Class Base View):

  1. convert URLconf.
  2. Delete unnecessary views.
  3. Create views based on Django’s generic views.

Correction URLconf polls/urls.py:

Correction views: polls/views.py

  • generic.ListView, generic.DetailView These are classes that abstract the process of handling specific objects, perform most of the basic processing called collectively Class Base View
  • template_name = polls/details.html: Specifies the template name instead of the default ("polls/question_detail.html")
  • context_object_name = 'latest_question_list' Specifies the return variable name for the template, otherwise in this context the default variable name will be question_list
  • get_queryset: There are a bunch of query helper methods called queryset, In this case, override the method to get 5 questions by pub_date.
Share the news now

Source : Viblo