Skip to main content
 首页 » 编程设计

python之Django 教程第 1 部分 'Poll' 对象没有属性 'was_published_today'

2024年09月03日28开发

我正在做这个 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 类)。