我是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工作
到目前为止,我已经尝试过:
模型
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'.
prepopulated_from=album_name
或prepopulated_fields=album_name
模特(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'
感谢您的帮助
答案 0 :(得分:2)
models.SlugField()
不支持prepopulated_from
或prepopulated_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",)}