我正在执行Django教程https://docs.djangoproject.com/en/dev/intro/tutorial01/,并且was_published_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。

最佳答案

我在阅读Django教程时遇到了类似的问题。我发现,为了选择自定义方法,我不得不退出Python Shell并重新启动它(并重新导入Poll类)。

09-25 17:43