django model get_absolute_url not working

时间:2017-08-23 02:29:12

标签: django django-models

我已经看到了一个直接在书中的模型实例上使用上述方法的例子。然而,这实际上并不起作用。是否在最新版本中删除了此方法?这是代码。

In [24]: django_tag
Out[24]: <Tag: Django>

In [22]: django_tag.get_absolute_url()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-22-bde20b3ec098> in <module>()
----> 1 django_tag.get_absolute_url()

AttributeError: 'Tag' object has no attribute 'get_absolute_url'

我看了dir函数。它没有显示这种方法存在。我正在使用django v.1.11。

In [25]: dir(django_tag)
Out[25]:
['DoesNotExist',
 'MultipleObjectsReturned',
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setstate__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_check_column_name_clashes',
 '_check_field_name_clashes',
 '_check_fields',
 '_check_id_field',
 '_check_index_together',
 '_check_local_fields',
 '_check_long_column_names',
 '_check_m2m_through_same_relationship',
 '_check_managers',
 '_check_model',
 '_check_model_name_db_lookup_clashes',
 '_check_ordering',
 '_check_swappable',
 '_check_unique_together',
 '_do_insert',
 '_do_update',
 '_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',
 '_save_parents',
 '_save_table',
 '_set_pk_val',
 '_state',
 'blog_posts',
 'check',
 'clean',
 'clean_fields',
 'date_error_message',
 'delete',
 'from_db',
 'full_clean',
 'get_deferred_fields',
 'id',
 'name',
 'objects',
 'pk',
 'prepare_database_save',
 'refresh_from_db',
 'save',
 'save_base',
 'serializable_value',
 'slug',
 'startup_set',
 'unique_error_message',
 'validate_unique']

models.py

class Tag(models.Model): 
    name = models.CharField(max_length=31, unique=True) 
    slug = models.SlugField(unique=True, help_text='A label for URL config.') 

    def __str__(self): 
        return self.name 

    class Meta: 
        ordering = ['name']

1 个答案:

答案 0 :(得分:0)

请阅读此docs

class Tag(models.Model):
    name = models.CharField(max_length=31, unique=True)
    slug = models.SlugField(unique=True, help_text='A label for URL config.')

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        from django.urls import reverse
        return reverse('appname.views.viewname', args=[self.slug])

    class Meta:
        ordering = ['name']