How to auto insert the current user when creating an object in django admin?(在 django admin 中创建对象时如何自动插入当前用户?)
问题描述
我有一个文章数据库
submitter = models.ForeignKey(User, editable=False)
其中User导入如下:
from django.contrib.auth.models import User. 
我想在特定用户提交文章时将当前活跃用户自动插入到提交者字段中.
I would like to auto insert the current active user to the submitter field when a particular user submits the article.
大家有什么建议吗?
推荐答案
以防万一有人在寻找答案,这是我在这里找到的解决方案:http://demongin.org/blog/806/
Just in case anyone is looking for an answer, here is the solution i've found here: http://demongin.org/blog/806/
总结一下:他有一个作文表如下:
To summarize: He had an Essay table as follows:
from django.contrib.auth.models import User
class Essay(models.Model):
    title = models.CharField(max_length=666)
    body = models.TextField()
    author = models.ForeignKey(User, null=True, blank=True)
其中多用户可以创建论文,所以他创建了一个admin.ModelAdmin类,如下:
where multiuser can create essays, so he created a admin.ModelAdmin class as follows:
from myapplication.essay.models import Essay
from django.contrib import admin
class EssayAdmin(admin.ModelAdmin):
    list_display = ('title', 'author')
    fieldsets = [
        (None, { 'fields': [('title','body')] } ),
    ]
    def save_model(self, request, obj, form, change):
        if getattr(obj, 'author', None) is None:
            obj.author = request.user
        obj.save()
                        这篇关于在 django admin 中创建对象时如何自动插入当前用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 django admin 中创建对象时如何自动插入当前用户?
				
        
 
            
        基础教程推荐
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
 - 包装空间模型 2022-01-01
 - 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
 - Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
 - 在Python中从Azure BLOB存储中读取文件 2022-01-01
 - PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
 - 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
 - 求两个直方图的卷积 2022-01-01
 - 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
 - 修改列表中的数据帧不起作用 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				