はじめての Django アプリ作成、その 4 (2)

帰宅。急いで emacs22 入れた。で、テンプレと views.py を utf-8-unix にして保存。なんか微妙なボケをカマしている事が判明。投票するのは良いのだけど、ラジオボタンみたいなソレが表示されとらん。
ちなみに emacs文字コードのナニは C-x RET f でした。
それは良いんですが Choice に何もデータが無いんだよねー。これが原因??
仕方が無いのでもう一度イチからドキュメント確認してみるか。

続き

で、その 1 から見てみたら最後の API でナニな項で Choice をいくつか作っている。スルーしてました。面倒だったので (を
作っておきましょうね。

$ python manage.py shell
Python 2.4.4 (#2, Apr  5 2007, 20:11:18) 
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> p = Poll.objects.get(pk=1)
Traceback (most recent call last):
  File "<console>", line 1, in ?
NameError: name 'Poll' is not defined
>>> from mysite.polls.models import Poll, Choice
>>> p = Poll.objects.get(pk=1)
>>> p.choice_set.create(choice='Not much', votes=0)
Traceback (most recent call last):
  File "<console>", line 1, in ?
  File "/usr/lib/python2.4/site-packages/django/db/models/fields/related.py", line 222, in create
    new_obj = self.model(**kwargs)
  File "/usr/lib/python2.4/site-packages/django/db/models/base.py", line 161, in __init__
    raise TypeError, "'%s' is an invalid keyword argument for this function" % kwargs.keys()[0]
TypeError: 'choice' is an invalid keyword argument for this function
>>> p
<Poll: Poll object>
>>> p.choice_set.create(choice='Not much', votes=0)
Traceback (most recent call last):
  File "<console>", line 1, in ?
  File "/usr/lib/python2.4/site-packages/django/db/models/fields/related.py", line 222, in create
    new_obj = self.model(**kwargs)
  File "/usr/lib/python2.4/site-packages/django/db/models/base.py", line 161, in __init__
    raise TypeError, "'%s' is an invalid keyword argument for this function" % kwargs.keys()[0]
TypeError: 'choice' is an invalid keyword argument for this function
>>> 

うーん。おかしいな。って models.py 見てみると Choice の定義が ...

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choise = models.CharField(maxlength=200)
    votes = models.IntegerField()
    def __unicode__(self):
        return self.choice

choise ぢゃなくって choice だし orz
で、修正して試験してみてるんですが通らない。あ、syncdb だ。これは微妙なボケだなぁ。でも syncdb してもカラム名は変わってない (当たり前
うーん。とりあえず choise のままで。
あと __str__ の戻りが choice になってるので choise に修正。とほほほ。これで動きました。ナチュラル杉。

コンテンツ再表示

http://localhost:8000/polls/1/ を開いてみたらラジオボタンが出てきたが文言が何も出力されておらぬ。テンプレ見てみると以下

<h1>{{ poll.question }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="/polls/{{ poll.id }}/vote/" method="post">
{% for choice in poll.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}"
     value="{{ choice.id }}" />
    <label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br />
{% endfor %}
<input type="submit" value="投票する" />
</form>

うーん。choice.choise だな。ダメダメです。で投票してみたら result.html も、な事が判明。もっかい最初から作るかな。一応 view が DRY 違反なソレの対処は試してから、にした方が良さげな感じではあるのですが。