It is a material for study sessions This time, I will explain Form by taking a side road from the tutorial of the head family. Before entering the Form, I will introduce a little about updating django and namespace of url.
Tutorial Tutorial Tutorial 1 Tutorial 2 Tutorial 3 Tutorial 4
Also, until the last time, I explained django1.8, but since django1.9 was released while I was skipping updates. In the following tutorials, we will explain django 1.9. Even if you change the version of django from 1.8 to 1.9, there is no special difference in the contents of tutorials 1 to 4.
Source → ʻee195d1`
You can update to the latest django (1.9.2 as of February 20, 2016) by typing the following command on the command line.
If you are using a virtual environment, don't forget to activate the virtual environment with workon
.
(tutorial)$ pip install --upgrade django
(tutorial)$ pip install --upgrade django
Collecting django
Using cached Django-1.9.2-py2.py3-none-any.whl
Installing collected packages: django
Found existing installation: Django 1.8.6
Uninstalling Django-1.8.6:
Successfully uninstalled Django-1.8.6
Successfully installed django-1.9.2
If it finishes normally, it will uninstall the already installed django (1.8.6 in this case) as described above, and install the latest django.
requirements.txt
In this tutorial, django is the only external library used so far, but the number of related libraries used in the future will increase steadily.
Which library are you using at that time? , Is the version of the library the same? It is difficult to check each time.
Fortunately, python has a package management system called pip
and a virtual environment called virtualenv
.
You will not often suffer from this problem.
To get a list of libraries used in the current environment, type the following command in the shell.
(tutorial)$ pip freeze
Django==1.9.2
wheel==0.24.0
By convention in python, this content is output as requirements.txt
.
Another person can install the required libraries by importing this file.
As you can see, the output contents also have a version number such as 1.9.2, so there is no need to worry about malfunctions due to different versions.
In the tutorial, I intended to put it already, but I did not create it, so I added it with commit: ʻee195d1`.
(tutorial)$ pip freeze > requirements.txt
Just redirect the contents of pip freeze
.
In the case of django, it is recommended to put it in the same hierarchy as manage.py
.
Use the pip install -r
command to import.
After confirming that it is workon
in the environment you want to import, after -r
Describe the path to the file you want to import (requirements.txt
).
(tutorial)$ pip install -r requirements.txt
If you already have a library installed and want to update its version
(tutorial)$ pip install -U -r requirements.txt
You need the-U
option like>. However, when I tried it at hand, it seems that if the version of pip is8.0.2
, it will be updated without adding it.
Source → bba5e4f
In Tutorial 3, I skipped the explanation of namespace conversion of url,
Considering the future, it is convenient to separate them, so set namespace to polls url.
To add it, just add namespace
to the argument of the ʻinclude` function.
tutorial/urls.py
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^polls/', include('polls.urls')),
]
↓ Add namespace
to the polls include argument
tutorial/urls.py
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^polls/', include('polls.urls', namespace='polls')),
]
Be careful not to mistake the position of the closing parenthesis as an argument of the url function.
If you set namespace, you can pull url in the form of namespace: hoge
.
The namespace can also be written in a higher hierarchy, such as ʻapi: polls: create. I added the prefix
poll_to the name of the include destination
polls / urls.py`,
If you use namespace, it will be unnecessary, so delete it.
polls/urls.py
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'(?P<pk>\d+)/$', views.detail, name='poll_detail'),
url(r'(?P<pk>\d+)/vote$', views.vote, name='poll_vote'),
url(r'(?P<pk>\d+)/results$', views.results, name='poll_results'),
]
↓ Since the namespace is cut, the prefix named poll_
becomes unnecessary.
polls/urls.py
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'(?P<pk>\d+)/$', views.detail, name='detail'),
url(r'(?P<pk>\d+)/vote$', views.vote, name='vote'),
url(r'(?P<pk>\d+)/results$', views.results, name='results'),
]
In django 1.9, instead of writing the namespace name in the include argument in
tutorial / urls.py
, You can also set it by writing ʻapp_name ='polls'in
polls / urls.py`. https://docs.djangoproject.com/en/1.9/releases/1.9/#passing-a-3-tuple-or-an-app-name-to-include
With this change, URLs are now pulled from names to polls: detail
instead of poll_detail
.
Please check the source difference for the corrected part.
By cutting the namespace, the polls
app will be more separated from the tutorial
project and will be easier to use in other projects.
With the previous method, if another application in the same project gives a name such as poll_detail
to the URL, an error will occur.
You need to care about the URL names of all the applications managed by the project.
On the other hand, namespace is used to avoid conflicting namespace
in root urls.py (tutorial / urls.py
).
You just have to be careful.
Now, let's finally get into the story of Form. Form is used to pass data in a certain format from the client to the server, as the English translation of "form, application form" means. In Tutorial 4, Form was written directly in the template, and the processing after receiving was written on the view side. However, templates and views correspond to View and Controller in the MVC model, and it is not good for logic to be included here. Also, in the current format, the display of the radio button is described in the template, and its validation (determination of whether the selected data is correct), Furthermore, the processing using the input value (voting processing) is described in the view. However, because the input items, validation for them, and processing using the data are closely related. I want to handle these together. Form classes are available in django for general input (text, selectlists, radio buttons, etc.) and We provide the validator (input check).
The Form class makes it easier to write tests for Honke Tutorial 5. You can easily increase the number of input items, and you can easily reuse them in other places. Moreover, by linking with the class-based general-purpose View, the description of the view can be further reduced and made easier to understand.
Source → 34698a1
First of all, let's try making a Form.
Create a file called forms.py
in the application folder and define the Form class in it.
For the Form class, set the field class as a member.
Please refer to the official document for the field class that can be set.
https://docs.djangoproject.com/en/1.9/ref/forms/fields/
For the time being, let's set CharField, which is a field for inputting characters. CharField needs to specify the maximum number of characters (max_length) as a required argument, so set 100 characters for the time being.
polls/forms.py
from django import forms
class MyForm(forms.Form):
text = forms.CharField(max_length=100)
Let's check the output to see what happens when we write this.
Start a python shell with ./manage.py shell
, create an instance of the Form class created earlier, and create an instance of the Form class.
Let's print it.
$ ./manage.py shell
(InteractiveConsole)
>>> from polls.forms import MyForm
>>> f = MyForm()
>>> print(f)
<tr><th><label for="id_text">Text:</label></th><td><input id="id_text" maxlength="100" name="text" type="text" /></td></tr>
You can see that the text type input tag is output as the output.
Since the field name is set to text
, you can also confirm that the character string Text
appears as the label.
Source → 34f4914
Next, let's make the created Form class html. First, write the creation of Form and the passing to the template in views.py.
polls/views.py
from .forms import MyForm
def form_test(request):
form = MyForm()
return render(request, 'polls/form.html', {
'form': form,
})
Next, let's prepare a template.
I specified a template path of polls / form.html
, so the location of the file is
It is polls / templates / polls / form.html
.
polls/templates/polls/form.html
<html>
<body>
<form>
{{ form }}
</form>
</body>
</html>
Now you should see the following string confirmed in the shell in {{form}}
.
<tr><th><label for="id_text">Text:</label></th><td><input id="id_text" maxlength="100" name="text" type="text" /></td></tr>
Finally, connect the form_test function and the url.
Let's add the url to polls / urls.py
.
polls/urls.py
urlpatterns = [
...
url(r'^form$', views.form_test),
...
]
After writing so far, start the test server with ./manage.py runserver
and check it with a browser.
The url is http: // localhost: 8000 / polls / form
.
screen
It's a murderous scene, but for the time being, you can see that there is one input box.
html source
The html source looks like this.
As expected, the {{form}}
part has been replaced.
Source → 06c8422
Well, the input box has been created, but there is no receiving process on the server side yet.
When sending data to the server in html, describe ** where ** ** how ** data is sent in the <form>
tag.
Write the attributes ʻaction and
method, respectively. Also, to send, you need to place the
submit button inside the