[PYTHON] DJango Note: From the beginning (using a generic view)

The general-purpose view allows you to create pages even shorter than shortcuts. http://docs.djangoproject.jp/en/latest/ref/generic-views.html

I've written a lot in views.py so far, but with a generic view you can shave it off.

Edit urls.py on the application side as follows.

polls/urls.py ######

from django.conf.urls import patterns, include, url
from django.views.generic import DetailView, ListView
from polls.models import Poll

urlpatterns = patterns('',	#Don't forget to return it to the empty state
    url(r'^$',
        ListView.as_view(
            queryset=Poll.objects.order_by('-pub_date')[:5],
            context_object_name='latest_poll_list',
            template_name='polls/index.html'
		)
	),
    url(r'^(?P<pk>\d+)/$',
        DetailView.as_view(
            model=Poll,
            template_name='polls/detail.html'
		)
	),
    url(r'^(?P<pk>\d+)/results/$',
        DetailView.as_view(
            model=Poll,
            template_name='polls/results.html'
		),
        name='poll_results'
	),
    url(r'^(?P<poll_id>\d+)/vote/$', 'polls.views.vote'),
)

Here, ListView and DetailView are shown.

First of all, in common, until now, on the views.py side

# def index..
	temp = loader.get_template('polls/index.html')

And

	return render_to_response('polls/detail.html',{	#..

The template was specified in the function like this,

# url(..
	# SomeView.as_view(..
		template_name = 'polls/index.html'

Substitute with one sentence. Each template is specified directly in URLconf. If you do not specify this, ‘appName / modelName_detail.html’ seems to be the default name, but creating a template with this file name is not good enough. Especially in this example, the template name is fogged by detail and results, so it's definitely not good.

Next, let's look at each type of general-purpose view.

First, ListView.

--queryset: Enter the data you want to display in the list (array).

--context_object_name: Specify the name of the queryset (if not specified, the name modelName_list is the default). In the template created so far, the received name was ‘latest_poll_list’, so change it to this (even if you edit the name on the template side, the result is the same).

DetailView。 #####

First, notice that the first argument of the url has changed slightly.

# before
	r'^(?P<poll_id>\d+)/$'
# after
	r'^(?P<pk>\d+)/$'

The data with ‘\ d +’ (one or more digits) as pk (PrimaryKey) is reflected in the template. Pk here is a cliché. There seems to be a slug, but I'm not sure at the moment.

--model: As it is, the model class is specified.

--name: You have set a name for the view. It seems that a URL that calls this view can be automatically generated (named pattern?).

Editing of URLconf is now complete. And if you've done so far

You don't need the index, detail, results functions of views.py anymore.

It's okay to erase it. However, let's leave only vote. And edit only one line as follows.

views.py ######

#def vote..
	return HttpResponseRedirect( reverse('poll_results', args=(pobject.id,)) )

The first argument of reverse has been changed from'polls.views.results' to'poll_results'. This is the name of the results page you set earlier, and reverse seems to automatically generate a URL according to the view from here.

This completes the switch to the general-purpose view.

If you check the operation, you can see that it works exactly the same as Last time. Obviously this is easier.

By the way, the tutorial is over.

For the time being, I'd like to review it with the book I was referring to in the past post DJango Memo: Basics of Blog Creation and try again at the same time.

And the next goal is to publish it on heroku.

Recommended Posts

DJango Note: From the beginning (using a generic view)
DJango Note: From the beginning (creating a view from a template)
DJango Memo: From the beginning (creating a view)
DJango Note: From the beginning (form processing)
DJango Note: From the beginning (simplification and splitting of URLConf)
DJango memo: From the beginning (using the management screen) my addictive point
Ajax in Django (using generic class view)
DJango memo: From the beginning (editing the management screen) There is a mystery
Run a Python file from html using Django
DJango Memo: From the beginning (Error screen settings)
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~
Study from the beginning of Python Hour8: Using packages
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 3 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 4 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 5 ~
A little bit from Python using the Jenkins API
Create a shogi game record management app using Django 4 ~ Create View ~
The story of a Django model field disappearing from a class
How to generate a query using the IN operator in Django
DJango Memo: From the beginning (more edits to the management screen)
Create a simple CRUD app using Django's generic class view
Do a search by image from the camera roll using Pythonista3
Django: Import a class from a string
Get the value from the [Django] Form
[Note] Using 16x2-digit character LCD (1602A) from Python with Raspberry Pi
Try using the Python web framework Django (1)-From installation to server startup
How to get a namespaced view name from a URL (path_info) in Django
Get news from three major mobile companies using Django and the News API
A useful note when using Python for the first time in a while
How to build an application from the cloud using the Django web framework
Download the file from S3 using boto.
Learning notes from the beginning of Python 1
Omit BOM from the beginning of the string
Create a graph using the Sympy module
Get a reference model using Django Serializer
A note on enabling PostgreSQL with Django
Use Django from a local Python script
Create a dataframe from excel using pandas
Add a layer using the Keras backend
Learning notes from the beginning of Python 2
Get only the text from the Django form.
A note about doing the Pyramid tutorial
Django note 4
How to uniquely identify the source of access in the Django Generic Class View
Django Note 5
[Django] Create a form that automatically fills in the address from the zip code
Using the 1-Wire Digital Temperature Sensor DS18B20 from Python on a Raspberry Pi
Django Note 1
Django note 3
Django note 2
Exclusive release of the django app using ngrok
A note on customizing the dict list class
Create a phylogenetic tree from Biopyton using ClustalW2
Write a TCP server using the SocketServer module
A note about the python version of python virtualenv
View drug reviews using a list in Python
Try modifying the TortoiseHg file view a bit
Finding the beginning of Abenomics from NT magnification 2
Django tutorial summary for beginners by beginners ④ (Generic View)
Operate the schedule app using python from iphone