PythonでのWebプログラミング
今朝起きたらカレンダーでアドベントカレンダー担当がでってビックリしたから、以下の記事は多分足りない部分が多いけど、読んだらちょっと面白そうと思われる人がいるんでしたら、遠慮なく、声かけて下さい。。。そしたらもうちょっと細かく説明する。
今回はその中の1つ、Djangoの使い方をもうちょっと細かく見るつもり。
Django
まず、djangoがまだインストールしていなければ、Debian系のLinuxシステムの場合は簡単に以下のコマンドでインストール出来る。
apt-get install python-django
Djangoはインストールし終わったら、新たなプロジェクトを作成して見よう。
django-admin.py startproject tester
このコマンドを実行すれば「tester」と言うフォルダが出来て、その中身は以下の通り、
/tester
manage.py
/tester
__init__.py
settings.py
urls.py
wsgi.py
このファイルの中に基本的にいじるファイルは「settings.py」と「url.py」のみ。
現状の何もないプロジェクトを一回動かして見たいでした、以下のコマンドはテストサーバを起動する。
python2 manage.py runserver

次のステップは「/tester/settings.py」の中にデータベースの設定。今回はmysqlを使うだけどDjangoはPostgres,sqlite3,Oracleも対応している。使うデータベースとpythonモジュールをインストール確認して。debian系だったら、Pythonモジュールは「python-mysqldb」と言われる。データベースとデータベースユーザを作ったから、「tester/settings.py」のDB部分に以下のように変更すれば完成。
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'tester', # Or path to database file if using sqlite3.
'USER': 'tester', # Not used with sqlite3.
'PASSWORD': 'unko', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
設定があっていれば、
python2 manage.py syncdb
のコマンドでDBのセットアップスクリプトが動かす。最初の質問はこのDjangoプロジェクトにスーパユーザを作成するかどうか。「yes」を答えて、次にそのユーザ名、eメール、パスワードを入力すれば、DB設定のインストールは完成。
次はこのプロジェクトのアプリを作成するので、
python2 manage.py startapp unko
を作成しよう。これ実行したらアプリディレクトリを以下の通りで作成する。
/unko
__init__.py
models.py
tests.py
views.py
こん回のアプリはシンプルはポールアプリ作成するつもりから、Djangoを使う場合は基本的にDBのデザインから始まるので「unko/models.py」で以下のような感じにしよう。
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Chose(models.Model):
poll = models.ForeignKey(poll)
choise = models.CharField(max_length=200)
votes = models.IntegerField()
このようなシンプルなコードで、Djangoはデータベーステーブルとテーブル接続APIも作成する。ただDjangoはまだこのアプリのアクセスパス知らないから「/tester/settings.py」の「INSTALLED_APPS」の最後に
'unko',
を追加する必要。「python2 manage.py syncdb」また実行すれば、新しく追加したテーブルをDBにも追加する。
次はadminサイトを有効するので先ほどの「/tester/settings.py」の「INSTALLED_APPS」へ、
'django.contrib.admin',
のコメントを外して「/tester/urls.py」の中に
from django.contrib import admin
admin.autodiscover()
とそのしたの
url(r'^admin/', include(admin.site.urls)),
のコメントも外しましょう。そしたらテストサーバを動かしたら、「0.0.0.0:8000/admin」へアドミン画面がアクセス出きるんだが、ログインしても何も出来ないから,「/unko/admin.py」のファイルを作成し、以下の通りにすればアドミンユーザはポールは作成出来るようになる。
from unko.models import Poll
from unko.models import Choise
from django.contrib import admin
class ChoiceInLine(admin.StackedInLine):
model = Choise
extra = 3
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields':['question']}),
('Date information', {'fields':['pub_date'], 'classes': ['collapse']}),
]
inlines = [ChoiceInline]
admin.site.register(Poll, PollAdmin)
この上のコードはアドミン画面作成だけではなく、ポールの作成画面ちょっと綺麗に整理するも!
「python2 manage.py syndb」をした後で、テストサーバからアクセス出来るようになる
「/tester/url.py」の中に以下の行を追加すればポールのURLルールは完成。見たら多分分かるだけど、regexでURLをマッチし、unkoアプリのviewsの部分にリダイレクトする感じ。
url(r'^polls/$', 'unko.views.index'),
url(r'^polls/(?P<poll_id>\d+)/$', 'unko.views.detail'),
url(r'^polls/(?P<poll_id>\d+)/results/$', 'unko.views.results'),
url(r'^polls/(?P<poll_id>\d+)/vote/$', 'unko.views.vote'),
次は「/unko/views.py」に見よう。元々からぽけど、先ほどのURLの部分のリダイレクトをカッチする関数を作る必要。以下のviewはindex,detail,vote,resultの四つのviewをを作成した。
その中voteの関数以外全てテンプレートも利用するので後シンプルなテンプレもはっておく。
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext
from unko.models import Poll, Choise
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
t = loader.get_template('polls/index.html')
c = Context({
'latest_poll_list': latest_poll_list,
})
return HttpResponse(t.render(c))
def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/detail.html', {'poll': p},
context_instance=RequestContext(request))
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choise = p.choise_set.get(pk=request.POST['choise'])
except (KeyError, Choise.DoesNotExist):
# Redisplay the poll voting form.
return render_to_response('polls/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
}, context_instance=RequestContext(request))
else:
selected_choise.votes += 1
selected_choise.save()
return HttpResponseRedirect(reverse('polls.views.results', args=(p.id,)))
def results(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/results.html', {'poll': p})
テンプレを利用するためtester/settings.pyのTEMPLATE_DIRSに好きなディレクトリを登録して、そのディレクトリの中にpollフォルダをつくって。
pollフォルダのなかに「index.html」を作成する。そのファイルは上のviewsのindexを呼び出す手Mプレになるから、以下ようにする際、あるポールを一覧を表示する。
pollフォルダのなかに「index.html」を作成する。そのファイルは上のviewsのindexを呼び出す手Mプレになるから、以下ようにする際、あるポールを一覧を表示する。
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
次はdetailed.htmlを以下の通りだと、ポールの選択をラジオボタン付きのフォームで表示する。
<h1>{{ poll.question }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="/polls/{{ poll.id }}/vote/" method="post">
{% csrf_token %}
{% for choise in poll.choise_set.all %}
<input type="radio" name="choise" id="choise{{ forloop.counter }}" value="{{ choise.id }}" />
<label for="choise{{ forloop.counter }}">{{ choise.choice }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
<h1>{{ poll.question }}</h1>
<ul>{% for choise in poll.choise_set.all %} <li>{{ choise.choice }} -- {{ choise.votes }} vote{{ choise.votes|pluralize }}</li>{% endfor %}</ul>
<a href="/polls/{{ poll.id }}/">Vote again?</a>
これよんだら多分分かりにくいけど何とかなるかも。。。。
Good blog. Keep sharing. I love them Are you also searching for Pay For Essay Online? we are the best solution for you. We are best known for delivering online essay writing services to students without having to break the bank
返信削除Your blogs are amazing. Keep sharing. I love them Are you also searching for help with my assignment? we are the best solution for you. We are best known for delivering the best urgent assignment help.
返信削除The world’s most trusted and safest crypto exchange platform that is known as Crypto.com also cares for the issues that Crypto.com users commonly face. Most of the login and mobile app issues that you usually face while using the Crypto.com login account can be fixed on your own.
返信削除Crypto.com Login |
Binance.com Login|
CoinSpot Login|
Make a bold fashion statement with the beth dutton blue hooded coat. Its exquisite craftsmanship and attention to detail will set you apart from the crowd.
返信削除At YSJ, we are a worldwide online store offering high-quality leather jackets, including the popular 6666 carhartt jacket. Check out our collection and enjoy free worldwide shipping
返信削除GLJ goes above and beyond to provide an exceptional buying experience. The packaging of my ted lasso zip up jacket was impressive, and it arrived in pristine condition. They really know how to make customers feel special
返信削除I look forward to finding more of this fantastic writing. I appreciate you sharing this website with my social media networks! Thanks, it's wonderful. Excellent delivery. Continue sharing
返信削除divorcio de nueva jersey