Django 1.11.8 - Slug - 意外的关键字参数

时间:2018-02-20 14:44:26

标签: python django slug django-1.11

我是django的新手,几天前我开始构建我的第一个应用程序。我首先阅读了MDN教程和Django教程 - 构建2"虚拟"应用

我目前正在尝试开发一个照片库应用,它将显示属于某个专辑的所有照片。我能够在我的urls.py和基于类的视图中实现这一点,但是,我希望使用更清晰的URL。我希望我的网址看起来像mysite.com/myapp/my-album-name vs mysite.com/myapp/1

我知道他们是这里提出的类似问题,我已经完成了大部分问题,阅读了Django关于Single Object Mixins,Class Based Views的文档,我仍然不明白如何让slu to工作

到目前为止,我已经尝试过:

  1. 在我的模型和相应的slug中实现一个slug字段 我的admin.py文件中的值:
  2. 模型

    class Album(models.Model):
        album_name = models.CharField(max_length=100, help_text="Enter the name of your album" )
        album_creation_date = models.DateField(auto_now_add=True)
        album_modified_date = models.DateField(auto_now=True)
        slug = models.SlugField(max_length=50)
    

    视图

    class albumPictures(generic.DetailView):
        model = Album 
    

    管理

    class AlbumAdmin(admin.ModelAdmin):
        list_display = ('album_name', 'album_creation_date')
        slug = prepopulated_fields = {'slug': (Album.album_name)}
    
    admin.site.register(Album, AlbumAdmin)
    

    错误消息: <class 'Albums.admin.AlbumAdmin'>: (admin.E030) The value of 'prepopulated_fields["slug"][0]' refers to '<django.db.models.query_utils.DeferredAttribute object at 0x107f234a8>', which is not an attribute of 'Albums.Album'.

    1. 在我的模型中使用prepopulated_from=album_nameprepopulated_fields=album_name
    2. 实施slug字段

      模特(1)

      class Album(models.Model):
          album_name = models.CharField(max_length=100, help_text="Enter the name of your album" )
          album_creation_date = models.DateField(auto_now_add=True)
          album_modified_date = models.DateField(auto_now=True)
          slug = models.SlugField(prepopulated_from=album_name)
      

      模特(2)

      class Album(models.Model):
          album_name = models.CharField(max_length=100, help_text="Enter the name of your album" )
          album_creation_date = models.DateField(auto_now_add=True)
          album_modified_date = models.DateField(auto_now=True)
          slug = models.SlugField(prepopulated_fields=album_name)
      

      视图

      class albumPictures(generic.DetailView):
          model = Album 
      

      错误消息: TypeError: __init__() got an unexpected keyword argument 'prepopulated_from'

      感谢您的帮助

1 个答案:

答案 0 :(得分:2)

models.SlugField()不支持prepopulated_fromprepopulated_fields,所以在你的模型中你应该使用

slug = models.SlugField(max_length=50)

而不是

slug = models.SlugField(prepopulated_from=album_name)

slug = models.SlugField(prepopulated_fields=album_name)

其次,在ModelAdmin课程中,您应该使用prepopulated_fields选项的字符串元组:

class AlbumAdmin(admin.ModelAdmin):
    list_display = ('album_name', 'album_creation_date')
    prepopulated_fields = {'slug': ("album_name",)}