Django教程第1部分'投票'对象没有属性'was_published_today'

时间:2011-07-10 12:54:21

标签: python django django-models

我正在做这个Django教程https://docs.djangoproject.com/en/dev/intro/tutorial01/并且was_ 已发布 _today无效。谢谢你的时间。

这是命令行:

    Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on
    win32
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>> from polls.models import Poll, Choice
    >>> Poll.objects.all()
    [<Poll: What's up?>]
    >>> Poll.objects.get(pk=1)
    <Poll: What's up?>
    >>> p = Poll.objects.get(pk=1)
    >>> p.was_published_today()
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
    AttributeError: 'Poll' object has no attribute 'was_published_today'

这是models.py

    # Create your models here.
    from django.db import models

    import datetime

    class Poll(models.Model):
        question = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
        def __unicode__(self):
            return self.question
        def was_published_today(self):
            return self.pub_date.date() == datetime.date.today()


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

    >>> dir (p)
    ['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict_
    _', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__
    ', '__metaclass__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_e
    x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
    _unicode__', '__weakref__', '_base_manager', '_collect_sub_objects', '_default_m
    anager', '_deferred', '_get_FIELD_display', '_get_next_or_previous_by_FIELD', '_
    get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_meta', '_
    perform_date_checks', '_perform_unique_checks', '_set_pk_val', '_state', 'choice
    _set', 'clean', 'clean_fields', 'date_error_message', 'delete', 'full_clean', 'g
    et_next_by_pub_date', 'get_previous_by_pub_date', 'id', 'objects', 'pk', 'prepar
    e_database_save', 'pub_date', 'question', 'save', 'save_base', 'serializable_val
    ue', 'unique_error_message', 'validate_unique']

注意:我也在使用instantdjango.com的Instant Django。

1 个答案:

答案 0 :(得分:3)

我遇到类似的问题,因为我正在通过Django教程。我发现,为了获取自定义方法,我不得不退出Python shell并重新启动它(并重新导入Poll类)。