怎么在表单中隐藏主键?

2017-02-28 23:51:49 +08:00
 lxy
class MusicInfo(models.Model):
    music_id = models.CharField(primary_key=True, default=hash_func)
    music_name =  # 略...

比如上面的 Model,music_id 是随机生成的哈希,在后台管理中会显示 music_id,我想在表单中隐藏这个字段,最好连 input hidden 标签也没有。

2995 次点击
所在节点    Django
5 条回复
cszeus
2017-03-01 01:41:25 +08:00
为什么要手动设置一个 id 呢,用自增的不好么
crystom
2017-03-01 01:41:25 +08:00
lxy
2017-03-01 01:56:20 +08:00
@cszeus 防爬虫枚举
013231
2017-03-01 02:29:57 +08:00
把该 Field 的 editable 设为 False 不就可以了吗?

https://docs.djangoproject.com/en/1.10/ref/models/fields/#editable

Field.editable

If False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True.
JerryZhang
2017-03-01 10:46:59 +08:00
1 、在 admin fields 中去掉 music_id
2 、在 admin list_display 加上 music_id
3 、重写 save 函数,在保存的时候如果 music_id 为空,则自动生成一个

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/343922

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX